'C++ Include Guards for Standard Headers

I am wondering if/ what include guards on files like windows.h, math.h, iostream, stdio... etc.

Since I have those headers included multiple times in different files. Do those files already have guards built in or is there a definition defined?

I am just wondering what the standards are for that kind of thing.



Solution 1:[1]

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. Aanother way, which is supported by many compilers, is to use #pragma once. This has the advantage of preventing collisions even if someone defines the same constant in another header file.

Solution 2:[2]

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 of NDEBUG.178

178 This is the same as the Standard C library.

Solution 3:[3]

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.

Solution 4:[4]

These files are located in /usr/include/ and subdirectories (at least on my debian laptop). Looking at /usr/include/stdio.h

shows a typical guard,

#ifndef _STDIO_H
# define _STDIO_H       1

And checking for cpp, grep __cplusplus,

#if !defined __cplusplus || defined __STDC_LIMIT_MACROS

...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jonathan Leffler
Solution 2 Community
Solution 3 Michael Petrotta
Solution 4 Christian Ternus