Compilation and linking
Turning C++ source into a program happens in two separate stages: the compiler translates each source file independently into an object file, then the linker stitches those object files together and resolves the names they refer to.
Detailed Explanation
Say you are building a log parser split across main.cpp, parser.cpp, and stats.cpp. Three things happen to each of those files, in order.
Preprocessing. The preprocessor is a text substitution pass. It pastes the contents of every #include directly into the file, expands macros, and evaluates #if/#ifdef conditionals. It does not understand C++ at all. The output is one long stream of code with no # directives left. That stream is called a translation unit.
Compilation. The compiler parses that translation unit, type-checks it, optimises it, and emits machine code into an object file (.o on Unix, .obj on Windows). Along with the code, the object file carries a symbol table. Every function or global variable the file defines becomes a defined symbol. Every one it uses but does not define becomes an undefined symbol the linker must find later.
Linking. The linker takes all the object files plus any libraries, matches each undefined symbol against a definition somewhere, patches the addresses in, and writes the executable.
This split is why C++ builds are fast to rebuild. Change one line in stats.cpp and only that file needs recompiling; the other object files are reused. It is also inherited from C, from an era when a whole program did not fit in memory at once.
The split explains the two error messages that confuse everyone at the start:
| Message | Stage | Meaning |
|---|---|---|
'parseLine' was not declared in this scope | compiler | No declaration was visible. The compiler does not know the name exists or what it returns. |
undefined reference to 'parseLine(std::string)' | linker | The declaration was visible, so the call compiled, but no object file supplied a body. |
The usual cause of the second is a function you declared in a header and never defined, or a .cpp you forgot to add to the build.
The linker also enforces the one-definition rule for anything with external linkage: exactly one definition across the whole program. Two .cpp files each defining int errorCount; at namespace scope gives you a duplicate symbol error.
Symbol names in the object file are not the names you wrote. Because C++ allows overloading, the compiler encodes the parameter types and namespace into the symbol — _Z9parseLineNSt7__cxx1112basic_stringIcEE rather than parseLine. That encoding is name mangling. C has no overloading and no mangling, so calling a C library from C++ requires extern "C", which tells the compiler to emit the plain unmangled name.
Libraries come in two forms. A static library (.a, .lib) is an archive of object files; the linker copies the parts you use into your executable, making it bigger but self-contained. A dynamic library (.so, .dll, .dylib) is loaded at run time, so the executable stays small and the library can be patched independently, at the cost of needing the right version present on the machine.
Code Examples
parser.hpp — the declaration. Tells the compiler the name and signature.
// parser.hpp — the declaration. Tells the compiler the name and signature.
#pragma once
#include <string>
int countErrors(const std::string& line);parser.cpp — the definition. Gives the linker a body to point at.
// parser.cpp — the definition. Gives the linker a body to point at.
#include "parser.hpp"
int countErrors(const std::string& line) {
return line.find("ERROR") != std::string::npos ? 1 : 0;
}main.cpp
// main.cpp
#include "parser.hpp" // without this include: "was not declared in this scope"
#include <iostream>
// Calling a C library from C++: extern "C" suppresses name mangling, so the
// linker looks for the symbol "compress", not "_Z8compressPKcm".
extern "C" int compress(const char* data, unsigned long len);
int main() {
std::cout << countErrors("2024-01-01 ERROR disk full") << '\n'; // prints: 1
}
// Compile both, then link:
// g++ -c main.cpp parser.cpp -> main.o parser.o
// g++ main.o parser.o -o parse
// Forgetting parser.o here gives: undefined reference to countErrors(...)Common Gotchas
Declaring is not defining
writing `int total;` in a header and including it in two `.cpp` files creates two definitions and a duplicate symbol error at link time. Use `inline int total = 0;` (C++17) or declare it `extern` in the header and define it in exactly one source file.
Link order matters with static libraries
most Unix linkers process arguments left to right and only pull in archive members that resolve a symbol already seen. Put libraries after the object files that use them, or you get undefined references to functions that are plainly in the archive.
Mismatched declarations link silently or not at all
if the header says `void log(int)` and the source defines `void log(long)`, mangling makes them different symbols, so you get an undefined reference rather than a type error. Always include a module's own header in its `.cpp` so the compiler cross-checks them.
Templates are not compiled where they are declared
a template is only turned into code when instantiated, which is why putting a template definition in a `.cpp` gives an undefined reference from every other file that uses it.