Skip to content

/errors/cpp/undefined-reference-to

C++ undefined reference to `function()' (ld returned 1 exit status)

The commands on this page have not been executed by our verification runner yet.updated
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

greet.h
void greet();
main.cpp
#include "greet.h"
int main() { greet(); }
bash
g++ main.cpp -o app            # fails: greet.cpp was not linked
g++ main.cpp greet.cpp -o app  # links both translation units

The 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

SymptomCauseFix
Your own functionIts .cpp is not in the buildAdd it to the command line or to target_sources / add_executable
Library function (pthread_create, curl_easy_init...)Library not linked or linked too earlyPut -lNAME after the objects: g++ main.o -lcurl
Name looks right but still undefinedSignature differs from the declaration (namespace, const, types)Make declaration and definition identical
Template function or class memberDefined in a .cpp fileMove the definition into the header
C function from C++ codeName manglingextern "C" around the C declarations
undefined reference to vtable for XA virtual function is declared but not definedDefine 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.

Sources