# Include guard

> Mediated Wiki article. Canonical URL: https://mediated.wiki/source/Include_guard
> Markdown URL: https://mediated.wiki/source/Include_guard.md
> Source: https://en.wikipedia.org/wiki/Include_guard
> Source revision: 1304369513
> License: Creative Commons Attribution-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-sa/4.0/)

{{short description|Construct in C and C++}}
{{Correct title|title=#include guard|reason=hash}}
{{Lowercase title}}
{{Technical|section|date=September 2018}}
In the [C](/source/C_(programming_language)) and [C++](/source/C%2B%2B) 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](/source/include_directive). 

The [C preprocessor](/source/C_preprocessor) processes inclusion directives like <code>#include "Foo.h"</code> to include "Foo.h" and [transcludes](/source/Transclusion) the code of that file into a copy of the main file often called the [translation unit](/source/Translation_unit_(programming)).

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](/source/compilation_error) due to the [One Definition Rule](/source/One_Definition_Rule), 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](/source/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](/source/Pragma_once). This non-standard but commonly supported directive among C and C++ [compilers](/source/List_of_compilers) has the same purpose as an #include guard, but has less code and does not require the definition of a variable.

[Modules](/source/Modules_(C%2B%2B)), introduced in [C++20](/source/C%2B%2B20), eliminate the necessity of <code>#include</code> guards, due to not being handled by the preprocessor. Modules can only be imported at most one time into a [translation unit](/source/Translation_unit_(programming)).

==Double inclusion==

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

==== File "Grandparent.h" ====
<syntaxhighlight lang="c">
struct Foo {
    int member;
};
</syntaxhighlight>

==== File "Parent.h" ====
<syntaxhighlight lang="c">
#include "Grandparent.h"

</syntaxhighlight>

==== File "Child.c" ====
<syntaxhighlight lang="c">
#include "Grandparent.h"
#include "Parent.h"

</syntaxhighlight>

==== Result ====
<syntaxhighlight lang="c">
struct Foo { // From "Grandparent.h"
    int member;
};
struct Foo { // From "Parent.h"
    int member;
};

</syntaxhighlight>Here, the file "Child.c" has indirectly included two copies of the text in the [header file](/source/header_file) "Grandparent.h". This causes a [compilation error](/source/compilation_error), since the structure type <code>Foo</code> will thus be defined twice. In C++, this would be called a violation of the [one definition rule](/source/One_Definition_Rule).

==Use of #include guards==

=== Example ===
The same code as the previous section is used with the addition of #include guards. The [C preprocessor](/source/C_preprocessor) preprocesses the header files, including and further preprocessing them [recursively](/source/Recursion_(computer_science)). This will result in a working source file.

====File "Grandparent.h"====
<syntaxhighlight lang="c">
#ifndef GRANDPARENT_H
#define GRANDPARENT_H

struct Foo {
    int member;
};

#endif /* GRANDPARENT_H */
</syntaxhighlight>

==== File "Parent.h" ====
<syntaxhighlight lang="c">
#include "Grandparent.h"
</syntaxhighlight>

==== File "Child.c" ====
<syntaxhighlight lang="c">
#include "Grandparent.h"
#include "Parent.h"
</syntaxhighlight>

==== Intermediate step ====

<syntaxhighlight lang="c">
// Contents from "Grandparent.h"
#ifndef GRANDPARENT_H // GRANDPARENT_H is not defined
#define GRANDPARENT_H

struct Foo { // This definition is compiled
    int member;
};

#endif /* GRANDPARENT_H */

// Contents from "Parent.h"
#ifndef GRANDPARENT_H // GRANDPARENT_H is already defined
#define GRANDPARENT_H

struct Foo { // This definition is not compiled
    int member;
};

#endif /* GRANDPARENT_H */
</syntaxhighlight>

==== Result ====
<syntaxhighlight lang="c">

struct Foo {
    int member;
};

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

=== Discussion ===
Different [naming conventions](/source/naming_conventions_(programming)) for the guard [macro](/source/macro_(computer_science)) may be used by different [programmer](/source/programmer)s. Other common forms of the above example include <code>GRANDPARENT_INCLUDED</code>, <code>CREATORSNAME_YYYYMMDD_HHMMSS</code> (with the appropriate time information substituted), and names generated from a [UUID](/source/Universally_Unique_Identifier). (However, [name](/source/identifier_(computer_programming))s starting with one underscore and a [capital letter](/source/capital_letter) (C and C++) or any name containing double underscore (C++ only), such as <code>_GRANDPARENT_H</code> and <code>GRANDPARENT__H</code>, are reserved to the language implementation and should not be used by the user.<ref>C++ standard (ISO/IEC 14882) section 17.4.3.1.2/1</ref><ref>C standard (ISO/IEC 9899) section 7.1.3/1.</ref>)

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 <code>[#pragma once](/source/pragma_once)</code> 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 <code>[#import](/source/Objective-C)</code> directive, which works exactly like <code>#include</code>, except that it includes each file only once, thus obviating the need for #include guards.<ref>{{Cite web|url=https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/DefiningClasses/DefiningClasses.html#//apple_ref/doc/uid/TP40011210-CH3-SW1|title=Objective C: Defining Classes|date=2014-09-17|website=developer.apple.com|language=en|access-date=2018-10-03}}</ref>

==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 <code>#pragma once</code>):

* [PL/I](/source/PL%2FI) uses the <code>%INCLUDE</code> statement as the equivalent to C's <code>#include</code> directive. IBM Enterprise PL/I also supports the <code>%XINCLUDE</code> statement which will "incorporate external text into the source program if it has not previously been included." (It also offers an <code>XPROCEDURE</code> statement, similar to a <code>PROCEDURE</code> statement, which will ignore the second and subsequent occurrences of an <code>XPROCEDURE</code> with the same name.) <ref>{{cite book |last1=IBM Corporation |title=Enterprise PL/I for z/OS PL/I for AIX Enterprise PL/I for z/OS Language Reference Version 5 Release 1 |date=August 2017 |page=257 |url=https://www.ibm.com/docs/en/SSY2V3_5.1.0/com.ibm.ent.pl1.zos.doc/lrm.pdf |access-date=Apr 7, 2022}}</ref>
* [Objective-C](/source/Objective-C)'s <code>#import</code> directive (see above)
* [PHP](/source/PHP)'s <code>include_once</code><ref>{{Cite web|url=https://www.php.net/manual/en/function.include-once.php|title= include_once (PHP Language Reference)}}</ref>

==See also==
*<code>[#pragma once](/source/Pragma_once)</code>
*[C preprocessor](/source/C_preprocessor)
*[Circular dependency](/source/Circular_dependency)
*[One Definition Rule](/source/One_Definition_Rule)
*[PL/I preprocessor](/source/PL%2FI_preprocessor)

==References==
<references/>

==External links==
*[https://web.archive.org/web/20100819052043/http://www.bobarcher.org/software/include/index.html Include guard optimisation]
*[http://c2.com/cgi/wiki?RedundantIncludeGuards Redundant Include Guards]

Category:C (programming language) headers

---
Adapted from the Wikipedia article [Include guard](https://en.wikipedia.org/wiki/Include_guard) by Wikipedia contributors ([contributor history](https://en.wikipedia.org/wiki/Include_guard?action=history)). Available under [Creative Commons Attribution-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-sa/4.0/). Changes may have been made.
