“未定义的参考"一个非常简单的c ++程序中的错误 [英] "undefined reference" error in a very very simple c++ program
问题描述
我有一个简单的程序,我完全从 http ://www.learncpp.com/cpp-tutorial/19-header-files/,因为我正在学习如何制作包含多个文件的c ++程序.
I have a simple program, which I copied exactly from the example in http://www.learncpp.com/cpp-tutorial/19-header-files/ because I'm learning how to make c++ programs with multiple files.
程序可以编译,但是在编译时会出现以下错误:
The program compiles but when building, the following error appears:
/tmp/ccm92rdR.o:在函数main中: main.cpp :(.text + 0x1a):对`add(int,int)'的未定义引用 collect2:ld返回1个退出状态
/tmp/ccm92rdR.o: In function main: main.cpp:(.text+0x1a): undefined reference to `add(int, int)' collect2: ld returned 1 exit status
代码如下:
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;
}
有人知道为什么会这样吗?
Does anyone knows why this happens?
非常感谢您.
推荐答案
该代码几乎是完美的.
The code is almost perfect.
添加一行#include "add.h" in
add.cpp`.
Add a line #include "add.h" in
add.cpp`.
将文件作为g++ main.cpp add.cpp
一起编译,将生成可执行文件a.out
Compile the files together as g++ main.cpp add.cpp
and it will produce an executablea.out
您可以将可执行文件作为./a.out
运行,它将产生输出"3和4之和为7"(不带引号)
You can run the executable as ./a.out
and it will produce the output "The sum of 3 and 4 is 7" (without the quotes)
这篇关于“未定义的参考"一个非常简单的c ++程序中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!