How to Fix C++ Undefined Reference Linker Errors
In this tutorial, you'll learn about How to Fix C++ Undefined Reference Linker Errors. We cover key concepts, practical examples, and best practices.
C++ undefined reference errors like undefined reference to 'foo()' occur when the compiler finds a declaration but the linker cannot find the corresponding definition across translation units or libraries.
Quick Fix
Wrong
// header.h
void foo();
// main.cpp
#include "header.h"
int main() { foo(); }
/tmp/main.o: In function `main':
main.cpp:(.text+0x5): undefined reference to `foo()'
The declaration exists in header.h, but foo() is never defined.
Right
// header.h
void foo();
// foo.cpp
#include <iostream>
void foo() { std::cout << "foo called\n"; }
// main.cpp
#include "header.h"
int main() { foo(); }
Compile together: g++ main.cpp foo.cpp -o app
foo called
Fix missing library link
#include <boost/algorithm/string.hpp>
int main() {
std::string s = "hello";
boost::to_upper(s);
}
undefined reference to `boost::algorithm::to_upper(...)'
g++ main.cpp -lboost_string_algorithms -o app
Fix C vs C++ linking
// C declaration in C++ code
extern "C" void c_function();
int main() { c_function(); }
g++ main.cpp c_library.o -o app
Prevention
- Always define functions in
.cppfiles, not.hfiles (unless inline or template). - Link all object files:
g++ a.o b.o c.o -o app. - Use
-l<library>for external libraries. - Wrap C headers with
extern "C"in C++ code. - Use CMake or Makefiles to track dependencies automatically.
DodaTech Tools
Doda Browser's C++ build analyzer parses linker errors and suggests missing libraries. DodaZIP archives build configurations for reproducible builds. Durga Antivirus Pro detects malicious library injection through linker paths.
Common Mistakes with undefined reference linker
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world CPP code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro