undefined reference to '...'
The undefined reference to '...' error means the linker knows about a symbol but cannot find its implementation. This is a linker error, not a compiler error.
What It Means
Your code calls a function or uses a variable that was declared (found its prototype or extern declaration) but never defined anywhere. The linker cannot resolve the address of that symbol.
Why It Happens
- A function was declared but never defined in any source file
- You forgot to link the required object file (
.o) or static library (.a) - A shared library (
.so/.dll) is not linked with the-lflag - The link order of libraries is wrong — the linker processes symbols left to right
- A C function is called from C++ without
extern "C"
How to Fix It
Step 1: Check for missing function definitions
// main.cpp
void declaredButNotDefined(); // declaration only, no definition
int main() {
declaredButNotDefined(); // linker error!
return 0;
}g++ main.cpp -o main
# Error: undefined reference to `declaredButNotDefined()'Fix: Provide the definition or remove the call.
Step 2: Link the correct object files
// helper.cpp
#include <iostream>
void printMessage() {
std::cout << "Hello from helper!" << std::endl;
}// main.cpp
void printMessage(); // declaration
int main() {
printMessage();
return 0;
}g++ -c helper.cpp -o helper.o
g++ -c main.cpp -o main.o
g++ main.o helper.o -o main # Both object files must be linkedForgetting helper.o causes: undefined reference to 'printMessage()'.
Step 3: Link libraries with the correct order
# Wrong order — may cause undefined references
g++ main.o -lfoo -o main
# Correct order — object files before libraries
g++ main.o -L/path/to/libs -lfoo -o mainThe linker resolves symbols left to right. Place dependent libraries after the objects that need them.
Step 4: Use extern "C" for C functions in C++
// C function declared in C++ without extern "C"
// This causes the linker to look for a C++ mangled name
extern void cFunction(); // wrong for C functions!
// Correct: tell the linker to use C naming
extern "C" {
void cFunction();
}g++ main.cpp c_helper.o -o mainStep 5: Verify function signatures match
Check for mismatched parameters between declaration and definition:
// header.h
void process(int value);
// impl.cpp
void process(double value) { } // different signature — different symbol!
The linker treats process(int) and process(double) as different symbols.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro