一个非常简单的 C++ 程序中的“未定义引用”错误

ona*_*rro 1 c++ linker header-files undefined-reference

我有一个简单的程序,我完全从http://www.learncpp.com/cpp-tutorial/19-header-files/ 中的示例中复制了该程序,因为我正在学习如何使用多个文件制作 C++ 程序。

程序可以编译,但是在构建时,出现以下错误:

/tmp/ccm92rdR.o: 在函数 main: main.cpp:(.text+0x1a): 对 `add(int, int)' 的未定义引用 collect2: ld 返回 1 个退出状态

这是代码:

主程序

#include <iostream>
#include "add.h" // this brings in the declaration for add()

int main()
{
    using namespace std;
    cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

添加.h

#ifndef ADD_H
#define ADD_H

int add(int x, int y); // function prototype for add.h

#endif
Run Code Online (Sandbox Code Playgroud)

添加.cpp

int add(int x, int y)
{
    return x + y;
}
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么会这样?

非常感谢。

Aru*_*run 5

代码几乎是完美的。

添加一行#include "add.h" inadd.cpp`。

将文件一起编译g++ main.cpp add.cpp,它将生成一个可执行文件a.out

您可以按以下方式运行可执行文件./a.out,它将产生输出“3 和 4 的总和为 7”(不带引号)