What is Header Guard in C++: Explanation and Example
header guard in C++ is a technique used to prevent a header file from being included multiple times in a single compilation, which can cause errors. It uses #ifndef, #define, and #endif preprocessor directives to ensure the file's content is only included once.How It Works
Imagine you have a recipe book, and you want to make sure you don't accidentally read the same recipe twice while cooking. A header guard works like a bookmark that tells you if you've already read that recipe. In C++, when you include a header file, the compiler copies its content into your code. If the same header is included multiple times, it can cause errors like duplicate definitions.
The header guard uses three preprocessor commands: #ifndef (if not defined), #define, and #endif. When the compiler first reads the header, it checks if a unique name (called a macro) is defined. If not, it defines it and includes the content. Next time, the macro is already defined, so the content is skipped, preventing multiple inclusions.
Example
This example shows a simple header guard in a header file named example.h. It prevents the content from being included more than once.
#ifndef EXAMPLE_H #define EXAMPLE_H void greet(); #endif // EXAMPLE_H
When to Use
Use header guards in every C++ header file you create. They are essential when your project grows and files include other files multiple times. Without header guards, you will get errors about redefinition of classes, functions, or variables.
For example, if two different source files include the same header, or if a header includes another header that is also included elsewhere, header guards keep the compiler from processing the same code repeatedly. This keeps your build clean and error-free.
Key Points
- Header guards prevent multiple inclusions of the same header file.
- They use
#ifndef,#define, and#endifpreprocessor directives. - Always add header guards to your header files to avoid compilation errors.
- They act like a safety check to include code only once.