Modern C++ • C++20 baseline
Headers, Translation Units, and the One Definition Rule
Organize declarations and definitions so multi-file programs link reliably.
Each source file is compiled as a translation unit. Headers publish declarations, normally protected by include guards or #pragma once. The One Definition Rule limits how entities may be defined across a program. Inline functions and templates have special rules, but ordinary non-inline function definitions generally belong in one source file.
Key points
- Include what you use directly.
- Keep implementation details out of public headers unless the language requires a definition there.
Example
// math.hpp
#pragma once
int add(int left, int right);
// math.cpp
#include "math.hpp"
int add(int left, int right) {
return left + right;
}
What to expect
The header declares add; the source file provides one definition that the linker can find.
Practice exercise
Split a small program into app.cpp, math.hpp, and math.cpp, then compile and link them together.
Key idea: A clean header boundary reduces coupling and prevents duplicate-definition problems.