1

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
  • 3
    The code is almost perfect. Include add.h in add.cpp. Compile it as g++ main.cpp add.cpp and it will produce a.out Commented Apr 4, 2013 at 2:54

2 Answers 2

5

The code is almost perfect.

Add a line #include "add.h" in add.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)

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you, Arun Saha, it worked perfectly. By the way, will I always have to compile together all the files I have in my program or is there an easier way?
You are welcome! You can compile each .cpp files separately into .o files respectively and finally link all the .o files to a single executable. Steps are: 1) g++ -c main.cpp 2) g++ -c add.cpp 3) g++ main.o add.o. However, once this quickly becomes tedious. In such situation, a tool is used to manage the compilation and linking of files. The tool is called make (en.wikipedia.org/wiki/Make_(software)) It works based on a configuration file, typically named Makefile, which you have to provide. You can search for and start with a simple Makefile
Thanks a lot! I was searching other websites for a simple straight answer but wasn't finding anything useful. I'll try that tool. :)
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.