0

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

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

头文件(test.h):

#include <iostream>
using namespace std;
#ifndef TEST_H
#define TEST_H

int foo (int bar);

#endif

功能(test.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;
}

当我尝试编译 drive.cpp 时,我收到以下错误:

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

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

4

4 回答 4

4

对于像这样的小项目,只需一次编译所有 .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

或者更确切地说,您将有一个 makefile 或 IDE 为您执行此操作。

于 2013-09-24T19:08:27.353 回答
2

在 drive.cpp 中,而不是

#include <test.h>

做了

#include "test.h"

#include这是用于您自己程序的头文件(不是系统头文件)的语法变体。当您使用此版本时,预处理器会按以下顺序搜索包含文件:

  • 在与包含#include 语句的文件相同的目录中。

  • 在任何先前打开的包含文件的目录中,以打开它们的相反顺序。搜索从最后打开的包含文件的目录开始,一直到最先打开的包含文件的目录。

于 2013-09-24T19:09:43.510 回答
1

您需要做以下两件事之一:

一次编译所有文件

# 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"

并把“使用命名空间标准;” 头文件中的内容会在以后给您带来极大的痛苦。

于 2013-09-24T19:11:17.620 回答
1

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

return bar++;
于 2013-09-24T19:12:26.287 回答