Inclusion Guards
Inclusion guards, also known as header guards, are a common technique used in C++ to prevent multiple inclusions of the same header file. Without inclusion guards, including the same header file multiple times in a project could lead to redefinition errors and increased compilation time.
These guards use preprocessor directives to ensure a header file is included only once during compilation.
Syntax
#ifndef MY_HEADER_H#define MY_HEADER_H// Header file content goes here#endif // MY_HEADER_H
Example
Let’s say there is a header file named example.h:
// example.h#ifndef EXAMPLE_H // Checks if EXAMPLE_H has been defined#define EXAMPLE_H // Defines it and includes the header contentvoid myFunction(); // Declare the function#endif // EXAMPLE_H
And your source file is main.cpp:
// main.cpp#include "example.h"#include "example.h" // This will be ignored due to the inclusion guardint main() {myFunction();return 0;}
The inclusion guard in example.h ensures that the content of the header file is only included once, even if it is included multiple times (as shown with the duplicate #include "example.h"
in main.cpp
). This avoids issues like redefinition errors or increased compilation time.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours