Saturday, September 6, 2008

Include Guard: #pragma once vs. #ifndef #define #endif

In the C and C++ programming languages, an include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of double inclusion when dealing with the #include directive. The addition of include guards to a header file is one way to achieve this. pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation. Both approaches specify that the file will be included only once by the compiler when compiling a source code file.

The table below compared the details of pragma once and #ifndef #define #endif approach:






















pragma once#ifndef #define #endif
Sample code
// header file
#pragma once
class foo { };

// header file 
#ifndef FOO_HEADER
#define FOO_HEADER
class foo { };
#endif // FOO_HEADER

C++ StandardNo

But both GCC and Microsoft Visual C++ support it.
Yes
Compiling PerformanceBetter

This can reduce build times as the compiler will not open and read the file after the first #include of the module.
It will still have to open the file multiple times, and discard the guard part when compiler find the macro guard. In a large project this could cause increased compile times.

But you can also optimize the compiling performance of #ifdef #define #endif approach by this way.

3 comments: