多文件C++编译
希望是我找不到答案的快速问题:多文件C++编译,c++,C++,希望是我找不到答案的快速问题: 我已经在C++中做了一个简短的作业。我们将编写一个3文件程序。将有一个函数文件、一个头文件和一个驱动程序文件。以下是到目前为止我得到的信息: 标题测试.h: #include <iostream> using namespace std; #ifndef TEST_H #define TEST_H int foo (int bar); #endif 那么…我做错了什么?对于这样的小项目,只需一次编译所有.cpp文件: g++ main.cpp d
我已经在C++中做了一个简短的作业。我们将编写一个3文件程序。将有一个函数文件、一个头文件和一个驱动程序文件。以下是到目前为止我得到的信息:
标题测试.h:#include <iostream>
using namespace std;
#ifndef TEST_H
#define TEST_H
int foo (int bar);
#endif
那么…我做错了什么?对于这样的小项目,只需一次编译所有.cpp文件:
g++ main.cpp driver.cpp
对于较大的项目,可以将编译和链接步骤分开:
汇编:
g++ -c main.cpp -o main.o
g++ -c driver.cpp -o driver.o
链接:
或者更确切地说,您需要一个makefile或IDE来为您执行此操作。在drive.cpp中,而不是
#include <test.h>
这是include语法的变体,用于您自己程序的头文件,而不是系统头文件。使用此版本时,预处理器将按以下顺序搜索包含文件:
与包含include语句的文件位于同一目录中
在以前打开的任何文件的目录中,包括与打开顺序相反的文件。搜索从上次打开的include文件的目录开始,然后继续搜索首先打开的include文件的目录
您需要做以下两件事之一: 一次编译所有文件
# replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o driver.exe main.cpp driver.cpp
将所有文件编译为目标文件,然后链接目标文件:
# again, replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o main.o -c main.cpp
g++ -Wall -ggdb -o driver.o -c driver.cpp
g++ -Wall -ggdb -o driver.exe main.o driver.o
作为旁注,您可能应该更改
#include <test.h>
使用名称空间std;在一个头文件中,稍后会给您带来大量痛苦。在test.cpp中,将返回行更改为:
return bar++;
include应该是include test.h出于对Stroustrup的喜爱,不要使用名称空间。。。在标题中,test.h和test.cpp没有理由包含。
#include "test.h"
# replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o driver.exe main.cpp driver.cpp
# again, replace 'driver.exe' with what you want your executable called
g++ -Wall -ggdb -o main.o -c main.cpp
g++ -Wall -ggdb -o driver.o -c driver.cpp
g++ -Wall -ggdb -o driver.exe main.o driver.o
#include <test.h>
#include "test.h"
return bar++;