C/C++: undefined reference to `function' — collect2: error: ld returned 1 exit status
The linker can’t find the definition of a function or variable that was declared and used.
Seen on:
C/C++
Meaning
The code compiled, but the object file or library containing the implementation wasn’t linked: a missing .cpp in the build, a missing -l library (or wrong order), C vs C++ name mangling, or a template defined only in a .cpp.
Common causes
- Source file defining the function not compiled/linked
- Library not linked or listed before the objects (-lfoo order)
- C function used from C++ without extern "C"
- Declaration and definition signatures differ
⚡ Quick fix
- Add the .cpp/.c to the build (CMake target_sources)
- Link the library after your objects (-lm, -lpthread, target_link_libraries)
- Wrap C headers in extern "C"
Detailed fix by platform
CMake
- cpp
add_executable(app main.cpp utils.cpp) target_link_libraries(app PRIVATE m pthread)
How to diagnose
- Symbol — Which name? (c++filt to demangle)
- Build — All sources compiled?
- Libraries — Linked and order
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- built for iOS, linking for simulator Building for iOS Simulator, but linking in object file built for iOS, for architecture arm64
- COPY failed COPY failed: file not found in build context / "/app/x": not found
- did not complete successfully failed to solve: process "/bin/sh -c ..." did not complete successfully: exit code: 1
Most viewed in C/C++
Other ways to find it
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
Was this page helpful?
Report a correction or suggest an improvement
Last updated 7 Oct 2026