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.

4 comments:

  1. Clear explaination and understood.

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

    ReplyDelete
  3. The Brother MFC-L2750DW across-the-board printer is intended for little workplaces. This monochrome laser printer offers print, sweep, copy, and fax works alongside wireless connectivity. The 2.7-inch brother touchscreen makes it simpler to work this multi-work printer. how to connect brother printer mfc l2750dw to wifi Notwithstanding, to really use every one of the highlights of this stunning Brother machine you should introduce it by using its certified Brother drivers. Along these lines, in this aide, we are giving you the Brother MFC-L2750DW driver download joins for Windows, Mac, and Linux working network. Albeit every one of the drivers shared beneath are real Brother printer drivers, we are as yet giving the Brothers official page interface which you can use to get other programming or drivers that have been delivered by the Brother for this multi-work printer.

    ReplyDelete