C++ Header Files
What Is a Header File?
A header file is a shared declaration file. It tells other .cpp files that a type, function, constant, or template exists. The header usually does not own the main implementation. It describes the interface that other source files can compile against.
A Minimal Header
This header declares a class. It says which constructors and member functions exist, but the function bodies can live in vector2.cpp.
What Belongs in a Header?
| Put in headers | Avoid in headers unless needed |
|---|---|
| Class declarations | Large function bodies |
| Function declarations | Non-inline global variable definitions |
| Small inline functions | Heavy includes that only the .cpp file needs |
| Templates, because their definitions must be visible | Anonymous namespaces |
| Constants intended for users of the API | Private helper functions that only one source file uses |
Include Guards and #pragma once
A header can be included more than once in the same translation unit through nested includes. Protection is mandatory.
The simple modern style:
The portable traditional style:
Forward Declarations
If a header only stores a pointer or reference to a type, it often does not need the full definition. A forward declaration can reduce compile-time dependencies.
The full Texture definition can be included in renderer.cpp, where the function body actually needs it.
A Bad Header Pattern
If this header is included by multiple .cpp files, the linker may see multiple definitions of global_counter and helper. That is why headers must be designed carefully.
What Comes Next
Headers declare the interface. Source files provide the implementation.