Creating basic include guards
What you'll learn: How to prevent "redefinition" errors by ensuring your header files are only read once by the compiler.
The problem: Double vision
Imagine you are following a recipe for a cake. Step 1 says to read the "Frosting Instructions." Step 5 also says to read the "Frosting Instructions." If you follow these directions literally, you might try to make the frosting twice at the same time, leading to a messy kitchen and confusion.
In C, your header files often contain definitions for structures or function prototypes. If main.c includes player.h, and it also includes game.h (which also includes player.h), the compiler sees the contents of player.h twice. It will throw an error because it thinks you are trying to define the same thing twice.
The solution: Include guards
An include guard is a simple gatekeeper. It uses preprocessor directives to ask a question: "Have I seen this file before?" If the answer is no, it reads the file. If the answer is yes, it skips everything.
We do this using three lines:
#ifndef: "If Not Defined"#define: "Define it now"#endif: "End of the gate"
Seeing it in action
Every time you create a .h file, you should wrap the entire contents like this:
/* player.h */
#ifndef PLAYER_H
#define PLAYER_H
// This structure will only be seen once by the compiler
struct Player {
int health;
int score;
};
void move_player(int x, int y);
#endif
How it works
The first time the compiler hits player.h, it checks if PLAYER_H is defined. It isn't, so it proceeds to the next line, defines PLAYER_H, and reads the struct.
If the compiler encounters player.h again later in the same build process, it hits the #ifndef PLAYER_H line. Since PLAYER_H was defined during the first pass, the check fails, and the preprocessor jumps straight to the #endif, effectively ignoring the rest of the file. No redefinition, no errors!
Key takeaway
Include guards act as a "do not repeat" sign, protecting your code from duplicate definition errors during the build process.