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

时间:2013-04-04 02:52:43

标签: c++ linker header-files undefined-reference multiple-files

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

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

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

以下是代码:

的main.cpp

#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;
}

add.h

#ifndef ADD_H
#define ADD_H

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

#endif

add.cpp

int add(int x, int y)
{
    return x + y;
}

有谁知道为什么会这样?

非常感谢。

2 个答案:

答案 0 :(得分:4)

代码几乎是完美的。

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

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

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

答案 1 :(得分:0)

当有许多.c或.cpp源并且其中一些未编译时,可能会发生未定义的引用。

关于如何做的一个好的“循序渐进”解释是here

相关问题