Organizing Header
& Source Files
Learn how to split your C++ code across .h/.hpp and .cpp files for clean, scalable, and error-free projects.
What Are Header and Source Files?
In C++, code is organized into two types of files that work together. Each plays a distinct role in the compilation process:
Why Separate Into Multiple Files?
The Compilation Pipeline
The One Definition Rule (ODR)
C++ enforces a strict rule: every function and variable may be defined (given a body or value) in exactly one translation unit. But it can be declared (announced to exist) in many units.
Declaration vs Definition
| Declaration | Definition | |
|---|---|---|
| Purpose | Announces a name exists | Provides the body or value |
| Where | .h / .hpp | .cpp |
| Can repeat? | Yes (in many files) | No (exactly once) |
| Function example | int add(int, int); |
int add(int a, int b) { return a+b; } |
| Variable example | extern int count; |
int count = 0; |
Include Guards Prevent Duplication
If main.cpp includes a.h and b.h, and b.h also includes a.h, the preprocessor will paste a.h contents twice. Include guards stop this:
How to Organize Your Files
g++ -c math.cpp, g++ -c main.cpp, then g++ math.o main.o -o program.Example 1: Simple Function Split
Example 2: Class Across Files
Example 2: Using the Class
Example 3: Multi-File Project Structure
What Goes Where?
| Element | Header (.h) | Source (.cpp) |
|---|---|---|
| Function prototype | ✓ | |
| Function body | ✓ | |
| Class definition | ✓ | |
| Method bodies | ✓ | |
| Constants (constexpr) | ✓ | |
| Global variable | extern only | ✓ definition |
| Inline functions | ✓ | |
| #include guards | ✓ | Not needed |
.h vs .hpp: What's the Difference?
Both extensions serve the same purpose. The distinction is purely a convention some teams adopt:
Common Mistakes to Avoid
Question 1 of 5
Which of the following should not be placed in a header file?
Question 2 of 5
What is the primary purpose of an include guard?
Question 3 of 5
You have main.cpp that uses functions from utils.h. Which compile command sequence is correct?
Question 4 of 5
A student writes #include "math.cpp" in their main file. What is the most likely result?
Question 5 of 5
In a Rectangle class split across files, where should the constructor body Rectangle::Rectangle(double w, double h) : width(w), height(h) {} be written?