HOME

TheInfoList



OR:

In the C and C++ programming languages, an #include guard, sometimes called a macro guard, header guard or file guard, is a way to avoid the problem of ''double inclusion'' when dealing with the
include directive An include directive instructs a text file processor to replace the directive text with the content of a specified file. The act of including may be logical in nature. The processor may simply process the include file content at the location of ...
. The
C preprocessor The C preprocessor (CPP) is a text file processor that is used with C, C++ and other programming tools. The preprocessor provides for file inclusion (often header files), macro expansion, conditional compilation, and line control. Although ...
processes inclusion directives like #include "Foo.h" to include "Foo.h" and transcludes the code of that file into a copy of the main file often called the translation unit. However, if an #include directive for a given file appears multiple times during compilation, the code will effectively be duplicated in that file. If the included file includes a definition, this can cause a compilation error due to the
One Definition Rule The One Definition Rule (ODR) is an important rule of the C++ programming language that prescribes that classes/structs and non-inline functions cannot have more than one definition in the entire program and templates and types cannot have more th ...
, which says that definitions (such as the definition of a class) cannot be duplicated in a translation unit. #include guards prevent this by defining a preprocessor macro when a header is first included. In the event that header file is included a second time, the #include guard will prevent the actual code within that header from being compiled. An alternative to #include guards is #pragma once. This non-standard but commonly supported directive among C and C++
compilers In computing, a compiler is a computer program that translates computer code written in one programming language (the ''source'' language) into another language (the ''target'' language). The name "compiler" is primarily used for programs tha ...
has the same purpose as an #include guard, but has less code and does not require the definition of a variable. Modules, introduced in
C++20 C20 or C-20 may refer to: Science and technology * Carbon-20 (C-20 or 20C), an isotope of carbon * C20, the smallest possible fullerene (a carbon molecule) * C20 (engineering), a mix of concrete that has a compressive strength of 20 newtons per squ ...
, eliminate the necessity of #include guards, due to not being handled by the preprocessor. Modules can only be imported at most one time into a translation unit.


Double inclusion


Example

The following C code demonstrates a real problem that can arise if #include guards are missing:


File "Grandparent.h"

struct Foo ;


File "Parent.h"

#include "Grandparent.h"


File "Child.c"

#include "Grandparent.h" #include "Parent.h"


Result

struct Foo ; struct Foo ; Here, the file "Child.c" has indirectly included two copies of the text in the
header file An include directive instructs a text file processor to replace the directive text with the content of a specified file. The act of including may be logical in nature. The processor may simply process the include file content at the location of ...
"Grandparent.h". This causes a compilation error, since the structure type Foo will thus be defined twice. In C++, this would be called a violation of the
one definition rule The One Definition Rule (ODR) is an important rule of the C++ programming language that prescribes that classes/structs and non-inline functions cannot have more than one definition in the entire program and templates and types cannot have more th ...
.


Use of #include guards


Example

The same code as the previous section is used with the addition of #include guards. The
C preprocessor The C preprocessor (CPP) is a text file processor that is used with C, C++ and other programming tools. The preprocessor provides for file inclusion (often header files), macro expansion, conditional compilation, and line control. Although ...
preprocesses the header files, including and further preprocessing them recursively. This will result in a working source file.


File "Grandparent.h"

#ifndef GRANDPARENT_H #define GRANDPARENT_H struct Foo ; #endif /* GRANDPARENT_H */


File "Parent.h"

#include "Grandparent.h"


File "Child.c"

#include "Grandparent.h" #include "Parent.h"


Intermediate step

// Contents from "Grandparent.h" #ifndef GRANDPARENT_H // GRANDPARENT_H is not defined #define GRANDPARENT_H struct Foo ; #endif /* GRANDPARENT_H */ // Contents from "Parent.h" #ifndef GRANDPARENT_H // GRANDPARENT_H is already defined #define GRANDPARENT_H struct Foo ; #endif /* GRANDPARENT_H */


Result

struct Foo ; Here, the first inclusion of "Grandparent.h" has the macro GRANDPARENT_H defined. When "Child.c" includes "Grandparent.h" at the second time (while including "Parent.h"), as the #ifndef test returns false, the preprocessor skips down to the #endif, thus avoiding the second definition of struct Foo. The program compiles correctly.


Discussion

Different
naming conventions A naming convention is a convention (norm), convention (generally agreed scheme) for naming things. Conventions differ in their intents, which may include to: * Allow useful information to be deduced from the names based on regularities. For ins ...
for the guard macro may be used by different
programmer A programmer, computer programmer or coder is an author of computer source code someone with skill in computer programming. The professional titles Software development, ''software developer'' and Software engineering, ''software engineer' ...
s. Other common forms of the above example include GRANDPARENT_INCLUDED, CREATORSNAME_YYYYMMDD_HHMMSS (with the appropriate time information substituted), and names generated from a
UUID A Universally Unique Identifier (UUID) is a 128-bit nominal number, label used to uniquely identify objects in computer systems. The term Globally Unique Identifier (GUID) is also used, mostly in Microsoft systems. When generated according to the ...
. (However,
name A name is a term used for identification by an external observer. They can identify a class or category of things, or a single thing, either uniquely, or within a given context. The entity identified by a name is called its referent. A person ...
s starting with one underscore and a
capital letter Letter case is the distinction between the letters that are in larger uppercase or capitals (more formally ''majuscule'') and smaller lowercase (more formally '' minuscule'') in the written representation of certain languages. The writing system ...
(C and C++) or any name containing double underscore (C++ only), such as _GRANDPARENT_H and GRANDPARENT__H, are reserved to the language implementation and should not be used by the user.) Of course, it is important to avoid duplicating the same include-guard macro name in different header files, as including the 1st will prevent the 2nd from being included, leading to the loss of any declarations, inline definitions, or other #includes in the 2nd header.


Difficulties

For #include guards to work properly, each guard must test and conditionally set a different preprocessor macro. Therefore, a project using #include guards must work out a coherent naming scheme for its include guards, and make sure its scheme doesn't conflict with that of any third-party headers it uses, or with the names of any globally visible macros. For this reason, most C and C++ implementations provide a non-standard #pragma once directive. This directive, inserted at the top of a header file, will ensure that the file is included only once. The Objective-C language (which is a superset of C) has an #import directive, which works exactly like #include, except that it includes each file only once, thus obviating the need for #include guards.


Other languages

Some languages support specifying that the code should be included only once, in the including file, rather than in the included one (as with C/C++ include guards and #pragma once): *
PL/I PL/I (Programming Language One, pronounced and sometimes written PL/1) is a procedural, imperative computer programming language initially developed by IBM. It is designed for scientific, engineering, business and system programming. It has b ...
uses the %INCLUDE statement as the equivalent to C's #include directive. IBM Enterprise PL/I also supports the %XINCLUDE statement which will "incorporate external text into the source program if it has not previously been included." (It also offers an XPROCEDURE statement, similar to a PROCEDURE statement, which will ignore the second and subsequent occurrences of an XPROCEDURE with the same name.) *
Objective-C Objective-C is a high-level general-purpose, object-oriented programming language that adds Smalltalk-style message passing (messaging) to the C programming language. Originally developed by Brad Cox and Tom Love in the early 1980s, it was ...
's #import directive (see above) *
PHP PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
's include_once{{Cite web, url=https://www.php.net/manual/en/function.include-once.php, title= include_once (PHP Language Reference)


See also

* #pragma once *
C preprocessor The C preprocessor (CPP) is a text file processor that is used with C, C++ and other programming tools. The preprocessor provides for file inclusion (often header files), macro expansion, conditional compilation, and line control. Although ...
* Circular dependency *
One Definition Rule The One Definition Rule (ODR) is an important rule of the C++ programming language that prescribes that classes/structs and non-inline functions cannot have more than one definition in the entire program and templates and types cannot have more th ...
* PL/I preprocessor


References


External links


Include guard optimisationRedundant Include Guards
C (programming language) headers