In C++, what problem do include guards solve, and how does #pragma once differ from an #ifndef guard?
answer
- one header reached twice
- redefinition inside one translation unit
- #ifndef, #define, #endif
- macro name versus file identity
- what the standard says about pragmas
basics
~20 sThey stop one header's text from being compiled twice in the same translation unit, which would redefine its classes. An #ifndef guard is standard and keyed by a macro name; #pragma once is a widely supported, non-standard pragma keyed by the file itself.
solid answer
~40 sThrough nested includes a `.cpp` file often reaches the same header twice: `main.cpp` includes `pose.h` and `planner.h`, and `planner.h` includes `pose.h` again. Without protection `struct Pose` is defined twice in one translation unit, and clang reports `redefinition of 'Pose'`. An **include guard** wraps the header in `#ifndef NAV_POSE_H` / `#define NAV_POSE_H` / `#endif`, so the second copy is skipped. `#pragma once` asks the compiler to remember the file and never read it again in that translation unit. It is shorter and cannot clash on a macro name, but the standard only says a pragma behaves in an implementation-defined way, and it depends on the compiler deciding that two paths name the same file. Neither form stops a header from being compiled once in **each** `.cpp` file.
code
plaintext · 7 linesIn file included from main.cpp:2:
./pose.h:1:8: error: redefinition of 'Pose'
1 | struct Pose {
| ^
main.cpp:1:10: note: './pose.h' included multiple times, additional include site here
main.cpp:2:10: note: './pose.h' included multiple times, additional include site here
./pose.h:1:8: note: unguarded header; consider using #ifdef guards or #pragma oncego deeper
Recall the three-line #ifndef, #define, #endif pattern and what it prevents: the same class defined twice in one .cpp file because two headers both include it.
Explain that guards work per translation unit, why the macro name must be unique and unreserved, and why #pragma once rests on the compiler's idea of the same file.
Diagnose the odd cases: declarations vanishing because two headers share a guard name, or a redefinition error from a vendored copy of a header that #pragma once treats as a new file.
Pick one convention for the codebase and enforce it with a check, knowing guards prevent an error but do nothing for build time, which needs include hygiene instead.
## Why the same header arrives twice `#include` pastes text. In a navigation codebase, `main.cpp` includes `pose.h` for `struct Pose` and `planner.h` for `class Planner`, and `planner.h` itself includes `pose.h` because a planner method returns a `Pose`. After preprocessing, `main.cpp`'s translation unit contains the text of `pose.h` twice. Nobody wrote the duplicate on purpose; it falls out of every header including what it needs, which is exactly what headers should do. The one-definition rule allows a class to be defined in many translation units, but **at most once in any one of them**. A second `struct Pose { ... };` in the same translation unit is an error. Apple clang 21 reports it as `redefinition of 'Pose'` and, helpfully, adds the note `unguarded header; consider using #ifdef guards or #pragma once`. ## The #ifndef guard The portable fix wraps the whole header in a conditional on a **controlling macro** (GCC's manual also calls it the guard macro): ```cpp // pose.h #ifndef NAV_POSE_H #define NAV_POSE_H struct Pose { double x, y, theta; }; #endif // NAV_POSE_H ``` The first inclusion finds the macro undefined, defines it and keeps the contents. Every later inclusion in the same translation unit finds it defined and skips everything up to `#endif`. GCC's manual adds that its preprocessor remembers such a wrapper and, while the macro stays defined, does not rescan the file at all. The guard is only as good as its name: - **It must be unique.** Two headers that share a guard name hide each other: whichever comes second is skipped, and its declarations seem to vanish, with "undeclared identifier" errors far from the cause. Copy-pasting a header and forgetting to rename the guard is the classic way in. - **It must not be reserved.** Identifiers that contain a double underscore, or begin with an underscore followed by an uppercase letter, are reserved to the implementation, so `_POSE_H` and `NAV__POSE_H` are not yours. Derive the name from the project and the path, such as `NAV_POSE_H`. ## #pragma once `#pragma once` at the top of the header replaces the three lines. The compiler records that file and refuses to read it again in that translation unit. GCC and clang both support it, as do most other compilers, and it removes the naming problems entirely. Its weak point is the question it rests on: *is this the same file?* The C++ standard does not define `#pragma once`; it says only that a `#pragma` causes the implementation to behave in an implementation-defined manner and that an unrecognised pragma is ignored. Each compiler decides sameness its own way. On this machine, with Apple clang 21, a symbolic link to the header was recognised as the same file, while a byte-identical **copy** of it at a second path was included again and produced the redefinition error. Vendored copies of a library and generated headers in two output folders are where that bites. GCC's own manual describes `#pragma once` as a less portable alternative to the `#ifndef` wrapper. | | `#ifndef` guard | `#pragma once` | |---|---|---| | In the ISO standard | yes, ordinary conditional compilation | no, an implementation-defined pragma | | Keyed by | a macro name you choose | the compiler's notion of file identity | | Failure mode | a duplicated or reserved macro name | the same header reached as two distinct files | | Boilerplate | three lines and a unique name | one line | Many codebases simply pick one by team rule; some write both. ## What neither one does - **They act per translation unit.** Each `.cpp` file starts afresh, with none of the guard macros defined, so every `.cpp` file that includes `pose.h` still compiles it once. A heavy header included by 400 files is parsed 400 times. - **They do not prevent duplicate definitions across files.** A non-inline function body in a guarded header is still defined once in every object file that includes it, and the link fails. That is a linkage question, not a guard question. - **They do not cut build time across the project.** Fewer includes, forward declarations, precompiled headers and C++20 modules do that; guards only prevent the error. - **They do not make a header self-sufficient.** A header that compiles only because its includer happened to include something else first is still fragile. Each header should include what it uses, so it compiles as the first line of any file.
- Why must a guard macro's name be unique, and which names are off limits?Two headers with the same guard macro hide each other: whichever is included second is skipped, and its declarations seem to vanish, with errors far from the cause. Identifiers containing a double underscore, or starting with an underscore and an uppercase letter, are reserved to the implementation, so `_POSE_H` is not yours. Build the name from the project and path, such as `NAV_POSE_H`.
- Do include guards make a header cheaper to compile across the whole build?Only inside one translation unit. Every `.cpp` file starts afresh, with none of the guard macros defined, so each one still opens and parses every header it reaches once: a heavy header included by 400 files is compiled 400 times. Cutting that takes fewer includes, forward declarations, precompiled headers or modules.
- Include guards stop a header's function bodies from clashing at link time.
- #pragma once is part of the ISO C++ standard.
- A guard named _POSE_H is fine because nothing else uses it.
- With include guards each header is parsed only once per build.
- Any two headers can share a guard name if their contents differ.