Traditionally, the standard and portable way to avoid multiple header inclusions in C++ was/is to use the #ifndef - #define - #endif
pre-compiler directives scheme also called macro-guard scheme (see code snippet below).
#ifndef MY_HEADER_HPP
#define MY_HEADER_HPP
...
#endif
In most implementations/compilers (see picture below) however, there's a more "elegant" alternative that serves the same purpose as the macro-guard scheme called #pragma once
. #pragma once
has several advantages compared to the macro-guard scheme, including less code, avoidance of name clashes, and sometimes improved compile speed.
Doing some research, I realized that although #pragma once
directive is supported by almost all known compilers, there's a turbidness on whether #pragma once
directive is part of the C++11 standard or not.
#pragma once
directive is part of the C++11 standard or not?#pragma once
).#pragma once
is not standard. It is a widespread (but not
universal) extension, which can be used
It was considered for standardization, but rejected because it cannot be implemented reliably. (The problems occur when you have files accessible through several different remote mounts.)
It's fairly easy to ensure that there are no include guard conflicts within a single development. For libraries, which may be used by many different developments, the obvious solution is to generate a lot of random characters for the include guard when you create it. (A good editor can be set up to do this for you whenever you open a new header.) But even without this, I've yet to encounter any problems with conflicts between libraries.