“undefined reference” error in a very very simple c++ program

旧时模样 提交于 2019-12-01 09:47:15

问题


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: In function main: main.cpp:(.text+0x1a): undefined reference to `add(int, int)' collect2: ld returned 1 exit status

Here's the code:

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?

Thank you very much.


回答1:


The code is almost perfect.

Add a line #include "add.h" inadd.cpp`.

Compile the files together as g++ main.cpp add.cpp and it will produce an executablea.out

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)




回答2:


Undefined references may happen when having many .c or .cpp sources and some of them is not compiled.

One good "step-by-step" explanation on how to do it is here



来源:https://stackoverflow.com/questions/15801727/undefined-reference-error-in-a-very-very-simple-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!