Header Files &
Include Guards
Learn how to organize C++ code into header files, prevent multiple inclusion errors, and write clean, modular programs.
What Is a Header File?
A header file is a file (usually ending in .h or .hpp) that contains declarations: function prototypes, class definitions, constants, and type aliases. It acts as a contract that tells other files what exists without revealing how things work.
Why Separate Headers and Source?
How #include Works
The #include directive is a preprocessor command. Before the compiler even sees your code, the preprocessor literally copies and pastes the entire contents of the included file into the current file.
The Multiple Inclusion Problem
If two files both #include the same header, and then a third file includes both of them, the header's contents get pasted multiple times. This causes redefinition errors at compile time.
Include Guards: The Solution
An include guard is a pattern using preprocessor directives that ensures a header's contents are only included once, no matter how many times the file is #included.
How the Guard Mechanism Works
#pragma once: The Modern Alternative
Most modern compilers support #pragma once, a simpler directive that tells the compiler to include the file only once per compilation unit. No macro name needed.
Include Guards vs #pragma once
| #ifndef / #define | #pragma once | |
|---|---|---|
| Standard | Official C++ standard | Non-standard (widely supported) |
| Syntax | 3 lines (ifndef, define, endif) | 1 line |
| Error risk | Typos in macro name | None |
| Portability | 100% portable | Nearly universal |
| Speed | Preprocessor re-reads file | Can be faster (skips file) |
Naming Your Include Guards
The guard macro name must be unique across your entire project. The convention is to use the filename in uppercase with underscores replacing dots and slashes.
Step-by-Step: Creating a Header
Example 1: Simple Header File
Example 2: Class in a Header
Example 3: Multi-file Project
Common Mistakes
Summary: What Goes Where?
| Element | Header (.h) | Source (.cpp) |
|---|---|---|
| Function prototypes | ✓ Yes | No |
| Function bodies | ✕ No | ✓ Yes |
| Class definitions | ✓ Yes | No |
| Method implementations | ✕ No | ✓ Yes |
| Constants / enums | ✓ Yes | No |
| Inline / template functions | ✓ Exception | Optional |
| Include guard / #pragma once | ✓ Always | Not needed |
Question 1 of 5
What is the primary purpose of an include guard in a C++ header file?
Question 2 of 5
Which of the following is the correct include guard pattern for a file named inventory.h?
Question 3 of 5
A student writes a function body (full implementation) inside a header file without the inline keyword, and two .cpp files include that header. What error will occur?
Question 4 of 5
What is one disadvantage of using #pragma once compared to traditional include guards?
Question 5 of 5
Why is the macro name _PLAYER_H (starting with underscore + uppercase) a bad choice for an include guard?