Back to questions
JuniorDebuggingCommon
How do you debug an 'undefined reference to' linker error?
A build compiles every translation unit cleanly but fails at the link step with this output. Walk through how you would track down the cause.
$ g++ -o app main.o -lutil
/usr/bin/ld: main.o: in function `main':
main.cpp:(.text+0x2a): undefined reference to `compute(int)'
/usr/bin/ld: main.cpp:(.text+0x41): undefined reference to `Logger::write(char const*)'
collect2: error: ld returned 1 exit statusDiagnose the cause.
Demangle with c++filt, then check: is the .cpp with the definition compiled and linked, is extern "C" missing, is the library linked — with GNU ld or gold, after the objects using it? nm shows if a symbol is defined, ldd the shared deps.
- Putting
-lfoobefore the objects that use it — GNU ld and gold do not go back to an earlier library (lld does) - Defining a function in a header and using it from multiple TUs without
inlineor template — multiple definition - Forgetting to link in
pthread,m,dl, etc.
- Why does GNU ld need a library after the objects that use it, while lld does not?
- How do you find which library provides a symbol on Linux?