Using #pragma once
in header files offers several advantages over traditional header guards:
With #pragma once
, you only need a single line at the beginning of the header file. It makes the code cleaner and more readable compared to header guards, which require three lines of code.
// MyHeader.h
#pragma once
// Header content goes here
When using header guards, you need to choose a unique name for each header file and ensure that the same name is used for the #ifndef
, #define
, and #endif
directives. With #pragma once
, you don't need to worry about unique names or maintaining the consistency of guard macros.
// MyHeader.h
#ifndef MYHEADER_H
#define MYHEADER_H
// Header content goes here
#endif
The #pragma once
directive is typically faster for the compiler to process compared to header guards. When the compiler encounters #pragma once
, it can quickly check if the header file has already been included and skip processing it again, improving compilation speed.
// MyHeader.h
#pragma once
// Header content goes here
Most modern compilers support #pragma once
, including GCC, Clang, and Microsoft Visual C++. However, if you need to support older compilers or ensure maximum portability, you can use a combination of #pragma once
and header guards, as shown in the example above.
// MyHeader.h
#if defined(__GNUC__) \
|| defined(__clang__) \
|| defined(_MSC_VER)
#pragma once
#else
#ifndef MYHEADER_H
#define MYHEADER_H
// Header content goes here
#endif
#endif
While #pragma once
offers several advantages, it's important to note that it's a non-standard extension. If portability across all compilers is a concern, you may still choose to use header guards. However, for most modern C++ projects, #pragma once
is widely supported and provides a simpler and more efficient way to prevent multiple header inclusions.
Answers to questions are automatically generated and may not have been reviewed.
Learn the fundamentals of the C++ build process, including the roles of the preprocessor, compiler, and linker.