How #pragma once works
What you'll learn: How to use a simple one-line command to prevent your compiler from getting confused by multiple copies of the same header file.
The Problem: The "Double-Included" Headache
In C, when you #include a file, the preprocessor literally copies and pastes the contents of that file into your code. As your projects grow, you might include player.h in your main.c, but also in inventory.h. If main.c then includes inventory.h, it accidentally brings in a second copy of player.h.
The compiler will see two identical sets of rules for the same "Player" structure and throw a "redefinition" error. It’s like trying to follow two identical sets of assembly instructions for the same Lego set at the same time—it’s redundant and confusing.
The Solution: A Simple Guard
#pragma once is a special instruction (a "directive") that you place at the very top of your header files. It tells the compiler: "Keep track of this file. If you see it again during this build, ignore it."
Think of it like a VIP guest list at a club. The first time the compiler sees the file, it reads it and adds the file's name to the list. If the compiler tries to enter the same file again later, it checks the list, sees it’s already been processed, and skips it.
How to use it
You don't need fancy logic or closing tags. You simply place it on the very first line of your .h file.
// player.h
#pragma once
struct Player {
int health;
int score;
};
void update_player(struct Player *p);
Even if ten different files in your project include player.h, the #pragma once directive ensures the struct Player definition is only processed once. This keeps your build clean and prevents those frustrating "redefinition of struct" errors.
Why use it?
While there is an older method called "Include Guards" (using #ifndef), #pragma once is the modern favorite. It is shorter, less prone to typing errors, and supported by almost every modern C compiler. It makes your headers cleaner and easier to read.
Key takeaway
#pragma once is a one-line insurance policy that prevents "redefinition" errors by ensuring a header file is only included once per build.