c++ – Protection against multiple connection of the header file

Question:

Which method is better to use:

#pragma once 

or

#ifndef XXX_H
#define XXX_H
...
#endif

Answer:

Both methods have their advantages and disadvantages.

#define cross-platform, conforms to the standard, is supported by all compilers, but it has an obvious drawback: if two header files with the same name happen to be in a project, unexplained errors are guaranteed. This is especially unpleasant in the case of large projects with 3rdparty code. You can come up with a more advanced scheme, in which the probability of collisions will decrease (for example, include the full path to the file in the project or the UUID in guard), but no one will give you a guarantee. (And you can't require third-party library developers to follow your standard.)

#pragma once free of these drawbacks because now your intent is communicated directly to the compiler, rather than through a low-powered preprocessor. But this format is not supported by all compilers, so there are likely to be portability issues.

Nevertheless, #pragma once supported by a large number of compilers , so if you rely only on popular compilers (MSVC, GCC, Clang, Intel compiler) of recent versions, it makes sense to stop at this option. Keep in mind that many experienced Unix developers dislike #pragma once , so you'll need to justify your choice.


If your code is part of a project, things get easier: just ask your project manager what is recommended. Choosing between include guard and #pragma once is part of the coding standards of any project.

Scroll to Top