Include Guards
Because #include performs a literal text paste, including the same header more than once inside one translation unit pastes its content in more than once too — and if that header defines a struct, a type, or anything else the compiler will not let you redefine, that duplicate paste turns into a compile error.
How the Duplicate-Include Problem Happens
This usually happens indirectly: a.h includes common.h, b.h also includes common.h, and some main.c includes both a.h and b.h. Without protection, common.h gets pasted into main.c twice, and the compiler sees its type definitions declared twice.
/* common.h — no protection */
struct Point {
int x;
int y;
};
/* main.c */
#include "a.h" /* a.h includes common.h */
#include "b.h" /* b.h also includes common.h */
/* error: redefinition of 'struct Point' */The Classic #ifndef Pattern
The traditional fix uses three directives working together as a one-time gate:
#ifndef COMMON_H
#define COMMON_H
struct Point {
int x;
int y;
};
#endif /* COMMON_H */#ifndef COMMON_H— "only proceed ifCOMMON_Hhas not been defined yet"The first time this header is included,
COMMON_His undefined, so the guard passes and#define COMMON_Himmediately marks it as now definedThe struct definition, function prototypes, etc. are processed normally the first time
Any later
#includeof the same header (in the same translation unit) findsCOMMON_Halready defined, so#ifndefis false and everything up to#endifis skipped entirely
The Modern Alternative: #pragma once
#pragma once
struct Point {
int x;
int y;
};Approach | Pros | Cons |
|---|---|---|
| Part of the C standard, works absolutely everywhere, maximum portability | More verbose, requires picking a unique guard name by hand |
| Short, no name to pick, avoids guard-name collisions | Not officially standardized (though universally supported in practice) |
You will still see the #ifndef pattern in codebases that target strict portability guarantees, older toolchains, or coding standards written before #pragma once became ubiquitous. Both approaches solve the exact same problem — pick whichever your project's style guide prefers, and use it consistently.