C++ Include Guards for Standard Headers
The C++ standard requires that the headers be organized such that you can include any of them multiple times, directly or indirectly, without running into problems. It doesn't mandate how that result will be achieved, just that it shall be achieved.
ISO/IEC 14822:2011
17.6.2.2 Headers [using.headers]
¶2 A translation unit may include library headers in any order (Clause 2). Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either
<cassert>
or<assert.h>
depends each time on the lexically current definition ofNDEBUG
.178178 This is the same as the Standard C library.
If you open the file to read the contents (you can even right click the include directive in most editors to open the file), you will see that include files usually start with something like:
#ifndef _WINDOWS_
#define _WINDOWS_
...
So the first time it will go in the file since _WINDOWS_
is not defined, therefore it will be defined and the contents of the file will be included. The second time the #ifndef
will fail since the define was done previously.
This is the standard way to put a safeguard, another way which is supported by many compilers is to put #pragma once
. This has the advantage to prevent collision in the case someone would define the same constant in another file for example.
Many compilers support #pragma once
. All of the standard libraries already have guards either in the form of #pragma once
or appropriate preprocessor macros. You can learn more about what the guards look like on the Wikipedia page. The fastest way to be sure is to right click on the include file definition and ask the development environment (Visual Studio/Eclipse) to open the file. Then you will see the guards.