C++ Reference ยท Preprocessor, Tools and Concepts
Include guards
Why headers need include guards, how the #ifndef/#define/#endif pattern prevents redefinition errors, how to name guards, and how #pragma once compares.
An include guard stops a header from being processed twice in the same translation unit. Because #include is plain text insertion, a header that is reached through two different paths (say a.h and b.h both include common.h, and main.cpp includes both) would have its declarations pasted twice. Declarations can usually repeat, but definitions such as struct Point { ... }; or an inline function cannot, and the compiler stops with a redefinition error.
The classic guard wraps the whole header in #ifndef NAME / #define NAME / #endif. The first time the file is read, NAME is undefined, so the body is kept and NAME gets defined. Every later inclusion sees NAME already defined and skips the entire body. The alternative #pragma once achieves the same with one line, relying on the compiler.
// point.h #ifndef MYPROJECT_GEOMETRY_POINT_H_ #define MYPROJECT_GEOMETRY_POINT_H_ struct Point { int x, y; }; #endif // MYPROJECT_GEOMETRY_POINT_H_
Try it
A runner program has one file, so we cannot show a real second include. Instead, this example pastes the same guarded block twice, which is exactly what the preprocessor does when a header is included twice.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.
Without the guards this is what GCC reports when a header is read twice (read-only):
error: redefinition of 'struct Point' note: previous definition of 'struct Point'
Syntax
// Option 1: portable include guard #ifndef UNIQUE_GUARD_NAME_H_ #define UNIQUE_GUARD_NAME_H_ /* header contents */ #endif // Option 2: compiler extension, supported everywhere in practice #pragma once /* header contents */
| Piece | Description |
|---|---|
| Guard name | A macro name that is unique across the whole program and all libraries it uses. |
#ifndef / #define |
Skip the body if the name is already defined; otherwise define it. |
#endif |
Ends the guarded region. The closing comment with the name helps readers. |
#pragma once |
Tells the compiler to remember this file and never read it again. |
Errors: a typo that makes two headers share a guard name silently drops the second one ("unknown type name" errors far from the cause). A guard that does not cover the whole file lets part of it be processed twice.
Usage notes
- Naming: use the project and the path, in upper case, with underscores:
MYLIB_NET_SOCKET_H_. Short names likeUTILS_Hcollide with other libraries. Never use names starting with an underscore followed by a capital letter or containing two underscores; they are reserved for the implementation. - Put the guard around the whole file, including every
#includeinside, and put nothing outside it except comments (so compilers can optimize repeated includes). - Every header gets one, including headers that "only" contain templates or inline functions. Only a deliberately multiple-include file (an X-macro
.deffile) has none; say so in a comment. #pragma oncepros and cons. Pro: shorter, no name collisions, can be faster. Con: not standard; it identifies a file by its location or contents, and with copies or links of the same file in different directories compilers can disagree. Major toolchains handle ordinary projects fine, so both are accepted practice; follow your project's style and do not mix them in one header.- Guards do not fix circular includes. If
a.hneedsb.handb.hneedsa.hthe guard just makes the second include empty and one of the types is missing. Break the cycle with a forward declaration (class B;) and include the full header only in the.cppfile. - Guards work per translation unit. Every
.cppfile still reads and parses the header. To reduce build time, keep headers small, use forward declarations, and consider precompiled headers or modules. - Guards do not prevent multiple definitions across files. A non-
inlinefunction defined in a header still gives a linker error when two.cppfiles include it. Make itinline,constexpr, a template, or move the definition into a.cppfile. - Modules (C++20) make guards unnecessary for code that is imported, though most code bases still use headers; our runner does not support modules.
Related
#include,#pragma,#if,#ifdef,#ifndef,inline, Modules- Lessons: Header files, The preprocessor