undefined reference to 🔧 C/C++

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

  1. Add the .cpp/.c to the build (CMake target_sources)
  2. Link the library after your objects (-lm, -lpthread, target_link_libraries)
  3. Wrap C headers in extern "C"

Detailed fix by platform

CMake

  1. cpp
    add_executable(app main.cpp utils.cpp)
    target_link_libraries(app PRIVATE m pthread)

How to diagnose

  1. Symbol — Which name? (c++filt to demangle)
  2. Build — All sources compiled?
  3. 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:

🧠 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.