01 / 21

Header Files &
Include Guards

Learn how to organize C++ code into header files, prevent multiple inclusion errors, and write clean, modular programs.

C++

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.

.h / .hpp
Contains declarations: function signatures, class outlines, constants
.cpp
Contains definitions: the actual implementation of functions and methods

Why Separate Headers and Source?

1
Code organization: Large projects split into many files. Headers let each file know about the others.
2
Faster compilation: Change one .cpp file and only that file needs to recompile, not the entire project.
3
Reusability: Other files simply #include your header to use your code.
4
Encapsulation: Users see the interface (header) without needing the implementation details (.cpp).

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.

math.h int add(int, int); int sub(int, int); // declarations copy main.cpp (after preprocessing) // pasted from math.h: int add(int, int); int sub(int, int); // your code: int main() { add(2, 3); sub(5, 1); }

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.

player.h physics.h #include "player.h" graphics.h #include "player.h" main.cpp ✕ error: redefinition of 'Player'

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.

player.h
#ifndef PLAYER_H #define PLAYER_H class Player { public: int health; void takeDamage(int dmg); }; #endif // PLAYER_H

How the Guard Mechanism Works

1st #include "player.h" #ifndef PLAYER_H PLAYER_H not defined ✓ #define PLAYER_H Now PLAYER_H = defined class Player { ... }; 2nd #include "player.h" #ifndef PLAYER_H PLAYER_H IS defined ✕ Skip entire file contents #endif Final compiled code Only ONE copy of Player ✓ No redefinition error

#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.

player.h
#pragma once class Player { public: int health; void takeDamage(int dmg); };

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.

1
player.h → PLAYER_H
2
game/engine.h → GAME_ENGINE_H
3
utils/math_helpers.hpp → UTILS_MATH_HELPERS_HPP

Step-by-Step: Creating a Header

1
Create the .h file with a clear, descriptive name (e.g., calculator.h).
2
Add the guard: write #ifndef CALCULATOR_H, then #define CALCULATOR_H on the next line (or use #pragma once).
3
Write declarations only: function prototypes, class definitions, constants, enums. Do not put function bodies here (with few exceptions).
4
Close with #endif (add a comment: // CALCULATOR_H for clarity).
5
#include your header in any .cpp file that needs its declarations.

Example 1: Simple Header File

calculator.h
#ifndef CALCULATOR_H #define CALCULATOR_H int add(int a, int b); int multiply(int a, int b); #endif // CALCULATOR_H
calculator.cpp
#include "calculator.h" int add(int a, int b) { return a + b; } int multiply(int a, int b) { return a * b; }

Example 2: Class in a Header

enemy.h
#pragma once #include <string> class Enemy { private: std::string name; int hp; public: Enemy(std::string n, int h); void takeDamage(int d); bool isAlive() const; };
enemy.cpp
#include "enemy.h" Enemy::Enemy(std::string n, int h) : name(n), hp(h) {} void Enemy::takeDamage(int d) { hp -= d; } bool Enemy::isAlive() const { return hp > 0; }

Example 3: Multi-file Project

utils.h enemy.h game.h enemy.cpp main.cpp game.cpp ✓ guard protects ✓ Compiles cleanly utils.h included once per unit

Common Mistakes

✕ Forgetting the Guard
Writing a header without #ifndef or #pragma once causes redefinition errors in any non-trivial project.
✕ Mismatched Macro Names
Using PLAYER_H in #ifndef but PLAYR_H in #define: the guard never activates, and the file is included every time.
✕ Definitions in Headers
Putting function bodies (not just declarations) in a header causes linker errors: "multiple definition of ..." across .cpp files.

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?