/errors/cpp/undefined-reference-to
C++ undefined reference to `function()' (ld returned 1 exit status)
- tool
- C++
- exit code
- 1
- versions
- GCC and Clang with GNU ld, gold, lld
- os
- linux, macos, windows
undefined reference to 'foo()' is a linker error, not a compiler error: every file compiled, but when the linker combined the object files and libraries it found no definition of foo(). The compiler accepted the call because it saw a declaration (in a header); the code that defines it was never linked. Add the missing .cpp file or library to the link command, or define the function. GCC ends the output with collect2: error: ld returned 1 exit status.
Example
void greet();#include "greet.h"
int main() { greet(); }g++ main.cpp -o app # fails: greet.cpp was not linked
g++ main.cpp greet.cpp -o app # links both translation unitsThe first command compiles main.cpp and then reports undefined reference to 'greet()' with the object and function where the call is, because no linked file defines greet().
Causes and fixes
| Symptom | Cause | Fix |
|---|---|---|
| Your own function | Its .cpp is not in the build | Add it to the command line or to target_sources / add_executable |
| Library function (pthread_create, curl_easy_init...) | Library not linked or linked too early | Put -lNAME after the objects: g++ main.o -lcurl |
| Name looks right but still undefined | Signature differs from the declaration (namespace, const, types) | Make declaration and definition identical |
| Template function or class member | Defined in a .cpp file | Move the definition into the header |
| C function from C++ code | Name mangling | extern "C" around the C declarations |
| undefined reference to vtable for X | A virtual function is declared but not defined | Define it (or make it pure with = 0) |
Library order
GNU ld resolves symbols left to right: a library is searched only for symbols that are still undefined at the point where it appears. g++ -lm main.o can fail where g++ main.o -lm works. When two libraries depend on each other, list one twice or use -Wl,--start-group ... -Wl,--end-group.