C++ Translation Units
Understand how header files and source files combine into translation units: the fundamental building blocks of the C++ compilation process.
What Is a Translation Unit?
A translation unit is the basic unit of compilation in C++. It consists of a single source file (.cpp) together with all the headers and other files it includes, after the preprocessor has finished expanding every #include directive.
Header vs Source Files
The Preprocessor Builds It
Before the compiler analyzes any C++ syntax, the preprocessor runs first. It processes directives that start with # and produces the final text that becomes the translation unit.
The Compilation Pipeline
The One Definition Rule (ODR)
The One Definition Rule is the core law governing translation units. It has two parts:
Include Guards Prevent Duplication
Declaration vs Definition
| Declaration | Definition | |
|---|---|---|
| Purpose | Tells compiler a name exists | Provides the full implementation |
| Where | Header file (.h) | Source file (.cpp) |
| Repetition | Can appear in many TUs | Must appear in exactly one TU |
| Example | int add(int, int); | int add(int a, int b) { return a+b; } |
ODR Exceptions: What Can Go in Headers
Some things are allowed (or even required) to appear in multiple translation units, as long as every copy is identical:
How to Organize a C++ Project
Example: Two-File Project
Tracing Translation Unit 1
When the compiler processes main.cpp, the preprocessor expands all #include directives. The resulting translation unit looks like this:
Example: Multi-Module Project
Internal vs External Linkage
Linkage determines whether a name defined in one translation unit can be referenced from another:
| Internal Linkage | External Linkage | |
|---|---|---|
| Visibility | Only in this TU | Across all TUs |
| Keywords | static, unnamed namespace | extern (default for functions) |
| Use case | Helper functions, file-local data | Shared APIs, global state |
| ODR scope | Each TU has its own copy | Must follow ODR across all TUs |
Common Mistakes with Translation Units
Summary: What Goes Where?
| Construct | Header (.h) | Source (.cpp) |
|---|---|---|
| Function declaration | ✓ | |
| Function definition | ✓ | |
| Class/struct definition | ✓ | |
| Inline function body | ✓ | |
| Template definition | ✓ | |
| Global variable definition | ✓ | |
| extern variable declaration | ✓ | |
| #include guards | ✓ |
Question 1 of 5
A translation unit in C++ is best described as:
Question 2 of 5
You define a non-inline function int compute(int x) in a header file that is included by three .cpp files. What happens?
Question 3 of 5
Which of the following is safe to place in a header file without causing ODR violations?
Question 4 of 5
What is the primary purpose of #pragma once (or #ifndef include guards)?
Question 5 of 5
A function marked static in a .cpp file has: