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

c++header-fileslinkerundefined-reference

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.

Best Solution

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)

Related Question