我有一个简单的程序,我完全从示例中复制了它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;
}
有谁知道为什么会发生这种情况?
非常感谢。
代码几乎是完美的。
添加一行#include "add.h"
in add.cpp
.
将文件一起编译为g++ main.cpp add.cpp
它会产生一个可执行文件a.out
您可以运行可执行文件./a.out
它将产生输出“The sum of 3 and 4 is 7”(不带引号)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)