A header file in C++ is a file, usually ending in .h or .hpp, that holds the declarations other files need to know about. Source files bring those declarations in with #include, and the matching .cpp file usually holds the actual function bodies.
What Goes in a Header File
A header typically contains:
- Function declarations, also called prototypes. They give a function’s name, return type and parameters, but not its body.
- Class, struct and enum definitions, so every file that uses the type sees the same layout.
- Constants, such as values declared with
constexpr. - Templates and
inlinefunctions. Their full definitions must be visible wherever they are used, so they normally live in headers. externdeclarations for variables defined in another file.
Ordinary function bodies usually go in .cpp files. The code is then compiled once and linked into the program, rather than repeated in every file that includes the header.
How #include Uses a Header
#include is a preprocessor directive. Before compiling, the preprocessor replaces that line with the text of the named file. You will usually see two forms:
#include "math_utils.h"is for your own headers. Compilers usually look first in the folder of the file doing the including.#include <iostream>is for system and standard library headers. Standard library headers such as<iostream>and<vector>have no file extension.
A Small Example
This example uses three files. The header declares a function, the source file defines it, and main.cpp calls it.
// math_utils.h
int add(int a, int b);
// math_utils.cpp
#include "math_utils.h"
int add(int a, int b) {
return a + b;
}
// main.cpp
#include <iostream>
#include "math_utils.h"
int main() {
std::cout << add(2, 3) << '\n';
return 0;
}
On a system with GCC or Clang, compile and run the program with:
g++ main.cpp math_utils.cpp -o app
./app
The program prints 5. The compiler checks the call in main.cpp against the declaration in math_utils.h, and the linker joins the compiled math_utils.cpp with main.cpp to make the final program. Other systems may use different commands.
Header Files Compared With Source Files
| File type | Usually holds | Example |
|---|---|---|
Header (.h, .hpp) |
Declarations, types, templates and inline functions |
int add(int a, int b); |
Source (.cpp) |
Function bodies and global variable definitions | int add(int a, int b) { return a + b; } |
Small programs can live in a single .cpp file with no header at all. Headers matter once a program is split across several files.
Why Headers Often Have a Header Guard
Most real headers also use a header guard in C, which keeps the same declarations from being read twice in one source file. Without one, a header included by two other headers can cause duplicate-definition errors. The math_utils.h above is small enough to skip the guard, but a larger header should have one.