What is Header Guard in C: Purpose and Example
header guard in C is a technique used to prevent a header file from being included multiple times in a program, which can cause errors. It uses #ifndef, #define, and #endif preprocessor directives to ensure the header content is included only once.How It Works
Imagine you have a recipe book and you want to make sure you don't accidentally copy the same recipe twice. A header guard works like a bookmark that says "I've already included this recipe." When the compiler processes your code, it checks if the header file has been included before. If it has, it skips it to avoid repeating the same definitions.
Technically, the header guard uses three preprocessor commands: #ifndef (if not defined), #define (define a name), and #endif (end if). The first time the header is included, the guard name is not defined, so the content is included and the name is defined. Next time, the name is already defined, so the content is skipped.
Example
This example shows a header file with a header guard to prevent multiple inclusions.
#ifndef MY_HEADER_H #define MY_HEADER_H void greet(); #endif // MY_HEADER_H // Implementation file #include <stdio.h> #include "my_header.h" void greet() { printf("Hello from header guard example!\n"); } // Main file #include "my_header.h" int main() { greet(); return 0; }
When to Use
Use header guards in every C header file you create to avoid problems caused by including the same file multiple times. This is especially important in large projects where many files include the same headers indirectly. Without header guards, you might get errors about redefined functions, variables, or types.
For example, if two different source files include the same header, or if a header includes another header that includes the first one again, header guards stop the repeated inclusion and keep your program compiling cleanly.
Key Points
- Header guards prevent multiple inclusions of the same header file.
- They use
#ifndef,#define, and#endifdirectives. - Always add header guards to your custom header files.
- They help avoid compilation errors like redefinition.
- Header guards improve code safety and maintainability.