多文件C++编译

Multi-file C++ compilation

本文关键字:编译 C++ 文件      更新时间:2023-10-16

(希望)我找不到答案的快速问题:

C++,我接到了一个简短的任务。我们要编写一个 3 文件程序。将有一个函数文件、一个头文件和一个驱动程序文件。这是我到目前为止得到的:

标头 (test.h):

#include <iostream>
using namespace std;
#ifndef TEST_H
#define TEST_H
int foo (int bar);
#endif

功能(测试.cpp):

#include <iostream>
#include "test.h"
using namespace std;
int foo (int bar){
    bar++;
}

驱动程序(驱动器.cpp):

#include <iostream>
#include "test.h"
using namespace std;
int main(){
    int x = foo(2);
    cout << x << endl;
    return x;
}

当我尝试编译驱动器.cpp时,出现以下错误:

drive.cpp:(.text+0xe): undefined reference to `foo(int)'

所以。。。我做错了什么?

对于这样的小项目,只需一次编译所有.cpp文件:

g++ main.cpp driver.cpp

对于较大的项目,您需要分开编译和链接步骤:

编译:

g++ -c main.cpp -o main.o
g++ -c driver.cpp -o driver.o

链接:

g++ main.o driver.o

或者更确切地说,你会有一个生成文件或IDE为你做这件事。

In drive.cpp,而不是

#include <test.h>

来得及

#include "test.h"

这是#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>

#include "test.h"

将"使用命名空间 std;"放在头文件中会在以后给您带来巨大的悲伤。

test.cpp 中,将返回行更改为:

return bar++;