0

Following the example here: http://www.learncpp.com/cpp-tutorial/19-header-files/

Relating to add.h and main.cpp

When I try to compile main.cc (I just used another extension), I get the following:

/tmp/cckpbRW.o:main.cc:(.text+0x9d):undefined reference to 'add(int, int)' collect2: ld returned 1 exit status

How can I fix this issue?

Thanks.

Simplicity
  • 47,404
  • 98
  • 256
  • 385

2 Answers2

3

Your didn't link your main object to your add one, so when the linker tries to build the executables it cannot find the definition of symbol add(int, int) it uses.

You should compile main object, add object and link them together, like this:

g++ -c -o main.o main.cpp
g++ -c -o add.o add.cpp
g++ -o executable main.o add.o

or

g++ -o executable main.cpp add.cpp

this will compile add.cpp and main.cpp together

peoro
  • 25,562
  • 20
  • 98
  • 150
  • Thanks for your reply. It worked now. So, is the "key" to compile them together? Why did you use "link them together" while what we are doing is compiling the two objects? Thanks. – Simplicity Jan 21 '11 at 15:43
  • @pero. If I use the first form of your solution I get the same error. I typed for example ---> g++ main.cc -o main.o (I'm using Cygwin). Why does the error appear? Thanks. – Simplicity Jan 21 '11 at 15:46
  • @SWEngineer: you need to use -c, to tell the compiler not to link, but just to compile (and/or assemble). Compilation of a program is made of several phases. The last one is linking, it's when you actually build your executable, putting in it all the things in your source files. – peoro Jan 21 '11 at 15:49
1

Looks like you are not linking the second .cpp file into final executable. Either compile and link them at the same time:

$ c++ -Wall -Werror -pedantic -g -otest1 add.cpp main.cpp

or compile them separately and then link:

$ c++ -Wall -Werror -pedantic -g -c main.cpp
$ c++ -Wall -Werror -pedantic -g -c add.cpp
$ c++ -Wall -Werror -pedantic -g -otest1 add.o main.o
Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171