Will be header included 2 times if I include another header which contains same header?

Will be header included 2 times if I include another header which contains same header?

Example code:

main header:

1
2
3
4
5
6
7
#ifndef MAIN
#define MAIN

#include <string>
#include "car.h" //Will this include string 2 times?

#endif 


car header:

1
2
3
4
5
6
#ifndef CAR
#define CAR

#include <string>

#endif 

Last edited on
My understanding is that the STL headers also have include guards like your car.h. Therefore, it will not be included twice. If anyone else has a different explanation then feel free.
From: https://en.wikipedia.org/wiki/Include_guard
In order 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
> Will this include string 2 times?

The effect would be as if <string> was included exactly once.

A translation unit may include library headers in any order. 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.
- IS
So solution is to add #pragma once?
No; the problem is already solved for standard headers. See JLBorges' quote for the relevant passage from the standard. For your own headers, you can choose to add #pragma once or add include guards.

I don't use #pragma in my code, because it eliminates the possibility of compatibility problems. Instead, I will write inclusion guards in my own header files that look like this:

<copyright info goes here>
...
# if ! defined <PROJECTNAME>_HEADER_<FILE_NAME>_HXX__
# define <PROJECTNAME>_HEADER_<FILE_NAME>_HXX__
...
<header file contents go here>
...
# endif

The disadvantage is that it's possible to have headers not be included (or defined again) if the symbol you use is defined elsewhere or undefined elsewhere. I've never had that problem.
Last edited on
Topic archived. No new replies allowed.