C++ - /tmp/cckpbRW.o:main.cc:(.text+0x9d):undefined reference [duplicate]
-
16-10-2019 - |
Question
This question already has an answer here:
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.
Solution
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
OTHER TIPS
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