C++ include guard
Asked Answered
P

3

6

So I know how to place an include guard in my own header files with the standard

#ifndef ...
#define ...

Now, My question is about including libraries that are not my own. would be a good example. I have a header file which requires the use of string, so I do the following

foo.h

#ifndef FOO_H
#define FOO_H

#include <string>

... code etc ...

#endif

Now, if I have another header file called.. lets say, bar.h, which ALSO requires the use of <string>, how can i prevent multiple inclusions? Does the STL already have include guards in place?

Princely answered 13/12, 2011 at 3:24 Comment(0)
D
12

The STL library also has include guards and any good library should do the same.

#ifndef _GLIBCXX_STRING
#define _GLIBCXX_STRING 1

This is from gcc's

Dowie answered 13/12, 2011 at 3:27 Comment(1)
Microsoft uses #pragma once - their proprietary version of header guards. Which is fine: the "STL" is nowadays part of the compiler, and therefore can use compiler-specific language extensions.Metalliferous
A
6

Assuming that by "STL" you mean the C++ standard library, then you can refer to the C++ standard. §17.6.2.2/2 states:

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.

This means that it is not necessary to guard against multiple inclusions of the same header.

Apollonian answered 13/12, 2011 at 3:38 Comment(0)
A
3

Include guard use to guard the content inside the guard pair. You can check the system head file string, it also has the include guard. So, don't worry about multiple inclusions.

Ansilma answered 13/12, 2011 at 3:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.