JuniorDebuggingCommonNot answered yet
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 status
Diagnose the cause.
Demangle with c++filt, then check: did you compile the .cpp with the definition, miss extern "C", get link order wrong, or forget the library? nm libfoo.a | grep sym shows whether it's defined; ldd binary shows resolved shared-library dependencies.
- ✗Putting
-lfoobefore the object that uses it — link order matters - ✗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 linker order matter for static libraries but not shared?
- →How do you find which library provides a symbol on Linux?