Pragma once
From Wikipedia, the free encyclopedia
- The correct title of this article is #pragma once. The substitution or omission of a # sign is because of technical restrictions.
In the C and C++ programming languages, #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. Thus, #pragma once
serves the same purpose as include guards, but in less code and without the possibility for name clashes.
See the article on include guards for an example of a situation in which one or the other of these methods must be used. The solution using include guards is given on that page; the #pragma once
solution would be
- File "grandfather.h"
#pragma once struct foo { int member; };
- File "father.h"
#include "grandfather.h"
- File "child.c"
#include "grandfather.h" #include "father.h"
[edit] Advantages and disadvantages
Using #pragma once
instead of include guards will increase compilation speed on many implementations, because 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
.
On the other hand, some compilers, such as GCC, also include special code to recognize and optimize the handling of include guards.[1]
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 H_GRANDFATHER
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 cuts both ways; 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 [2][3] and GCC as of 1998.[4] As of 2005, the GCC documentation lists #pragma once
as an "obsolete" feature.[5]