C++ Include Guards for Standard Headers

2019-06-18 23:46发布

问题:

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.

回答1:

Man, you are incredibly lazy, just open the file (you can even right click the include directive in most editors) and it starts 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.



回答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.



回答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.



回答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

...