Saturday, November 10, 2012


#pragma once

I just wondered what the differences between #pragma once and safeguard are. So I found a useful information from Wikipedia

 Advantages and disadvantages

Using #pragma once instead of include guards will typically increase compilation speed since it is a higher-level mechanism; the compiler itself can compare filenames or inodes without having to invoke the C preprocessor to scan the header for #ifndef and #endif.
Common compilers such as GCC, Clang, and EDG-based compilers include special speedup code to recognize and optimize the handling of include guards, and thus little or no speedup benefit is obtained from the use of #pragma once.[2][3][4]
Again because the compiler itself is responsible for handling #pragma once, it is not necessary for the programmer to create new macro names such as GRANDPARENT_H in the Include guard article's example. This eliminates the risk of name clashes, meaning that no header file can fail to be included at least once.
However, this high-level handling is not perfect; the programmer must rely on the compiler to handle #pragma once correctly. If the compiler makes a mistake, for example by failing to recognize that two symbolic links with different names point to the same file, then the compilation will fail. Compilers with #pragma once-related bugs included LCC-Win32 as of 2004[citation needed][5][6] and GCC as of 1998.[7] GCC originally gave a warning declaring #pragma once"obsolete" when compiling code that used it. However, with the 3.4 release of GCC, the #pragma once handling code was fixed to behave correctly with symbolic and hard links. The feature was "un-deprecated" and the warning removed.[8][9]
Both #pragma once and include guards can be used to write portable code that can also take advantage of the #pragma once optimization if the compiler supports it:
File "grandparent.h"
#pragma once
#ifndef GRANDPARENT_H
#define GRANDPARENT_H
 
struct foo
{
    int member;
};
 
#endif /* GRANDPARENT_H */

Portability

Compiler#pragma once
ClangSupported[10]
Comeau C/C++Supported[11]
Digital Mars C++Supported[12]
GCCSupported[13]
Intel C++ CompilerSupported[14]
Microsoft Visual C++Supported[15]
C++Builder XE3Supported[16]

                                       From Wikipedia <http://en.wikipedia.org/wiki/Pragma_once>

No comments:

Post a Comment