Library of Graphics

Library of Graphics

Computer Graphics: Fundamental and Practice

Library of Graphics RSS Feed
Search
 
 
 
 

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++ Standard No

But both GCC and Microsoft Visual C++ support it.

Yes
Compiling Performance Better

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.

2 Responses to “Include Guard: #pragma once vs. #ifndef #define #endif”

  1. 1
    Karmegam:

    Clear explaination and understood.

  2. 2
    SomeCoder:

    Any idea whether the pragma statment will be included in the new C++ standard (C++0x)?

Leave a Reply