“undefined reference” error in a very very simple

2019-02-20 11:07发布

问题:

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