The directive #pragma once
is used to ensure that the same file
(usually a C++ header file) is included only once. This actually
requires the compiler to be able to determine whether two files are
the same, under the possible presense of hard links and symbolic
links.
Header guards are more error-prone compared to #pragma once
.
-
A programmer can never be sure that one guard is not already used in anotehr header file. In case we have two files with the same guard:
-
file 1:
#ifndef MY_VERY_UNIQUE_HEADER_GUARD_H #define MY_VERY_UNIQUE_HEADER_GUARD_H ... #endif // MY_VERY_UNIQUE_HEADER_GUARD_H
-
file 2:
#ifndef MY_VERY_UNIQUE_HEADER_GUARD_H #define MY_VERY_UNIQUE_HEADER_GUARD_H ... #endif // MY_VERY_UNIQUE_HEADER_GUARD_H
This is called name clash. Only one of them will be included, and the other one will be dropped SILENTLY. This is bad.
-
-
Although you can follow some rules to dramatically lower the risk of name clash, they can still happen. For example:
- Usually the header guard follows the relative path of the header file within the projects. When the header file is moved, the programmer have to remember to modify the guard accordingly, which one does not always do.
- Sometimes the header (therefore the guard as well) is even generated by tools, such as Protobuf compiler.
Use #pragma once
if not contrained by consistency requirement.