Which method is better to use:

#pragma once 

or

 #ifndef XXX_H #define XXX_H ... #endif 

    1 answer 1

    Both methods have advantages and disadvantages.

    #define cross-platform, conforms to the standard, supported by all compilers, but it has an obvious disadvantage: if there are two header files with the same name in the project, inexplicable 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 a collision decreases (for example, to include in guard the full path to the file in the project or the UUID), but no one will give you a guarantee. (And you will not be able to require third-party library developers to follow your standard.)

    #pragma once devoid of these shortcomings, because now your intention is directly communicated to the compiler, and not through a low-power preprocessor. But this format is not supported by all compilers, so surely there will be problems with portability.

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


    If your code is part of a project, everything becomes simpler: just ask the project manager what is recommended for use. The choice between include guard and #pragma once is part of the coding standards of any project.

    • No words, great answer, thanks! - Unknown
    • @Unknown: Please! - VladD