The Compile–Link–Load Toolchain

an include guard

Headers often include other headers, so the same file can easily get pasted in twice. Imagine two of your files both #include the same types.h; if a third file pulls in both of them, the contents of types.h arrive twice. For some things, like defining a struct, getting it twice is an outright error: 'redefinition'. An include guard is a small standard trick that makes a header safe to include any number of times, pasting its body in only the first time and skipping it after.

The mechanism is three preprocessor lines wrapped around the whole header. At the top you write #ifndef SOME_UNIQUE_NAME then #define SOME_UNIQUE_NAME, and at the very bottom #endif. Read it as a sentence: 'if this unique name has NOT yet been defined, then define it now and keep everything below; otherwise skip to the bottom'. The first time the header is pasted in, the name is not yet defined, so the body is kept and the name gets defined as a side effect. Every later time, the name is already defined, so the whole body is thrown away. The name just needs to be unique to that header, by convention something like MYPROJECT_TYPES_H.

Almost every C and C++ header you will ever open begins with this pattern, and forgetting it is a common cause of baffling 'redefinition' errors during compilation. Many compilers also accept a single non-standard line, #pragma once, at the top of the file to achieve the same effect more briefly; it is widely supported but not part of the official language, so portable code often still uses the classic three-line guard.

#ifndef MYPROJECT_TYPES_H /* if not yet defined... */ #define MYPROJECT_TYPES_H /* ...define it, and keep going */ struct Point { int x, y; }; #endif /* MYPROJECT_TYPES_H */ /* second include skips straight here */

The body is included exactly once no matter how many times the header is pulled in.

The guard name must be unique across the whole project; two headers accidentally sharing a guard name will silently make one of them empty, since the second one's body is always skipped.

Also called
header guardinclude-once guard引入防護標頭防護