Jump to content

Pragma once: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
→‎Portability: Order + Pelles C
Line 58: Line 58:
| [[Microsoft Visual C++]] || Supported<ref>http://msdn.microsoft.com/en-us/library/4141z1cx%28v=vs.71%29.aspx</ref>
| [[Microsoft Visual C++]] || Supported<ref>http://msdn.microsoft.com/en-us/library/4141z1cx%28v=vs.71%29.aspx</ref>
|-
|-
| [[Pelles C]] || Supported<ref>IDE help/documentation</ref?
| [[Pelles C]] || Supported<ref>IDE help/documentation</ref>
|-
|-
|}
|}

Revision as of 09:29, 30 April 2013

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 with several advantages, including: less code, avoiding name clashes, and sometimes improved compile speed.[1]

Example

File "grandparent.h"
#pragma once

struct foo 
{
    int member;
};
File "parent.h"
#include "grandparent.h"
File "child.c"
#include "grandparent.h"
#include "parent.h"

Advantages and disadvantages

Using #pragma once instead of include guards will for some compilers 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.

GCC originally gave a warning declaring #pragma once "obsolete" due to a problem with symbolic and hard links. However, this problem was fixed in GCC 3.4, and the feature was "un-deprecated" and the warning removed.[5] Furthermore, #pragma once was removed from the list of obsolete features in GCC 4.4. [6]

Portability

Compiler #pragma once
Clang Supported[7]
Comeau C/C++ Supported[8]
C++Builder XE3 Supported[9]
Digital Mars C++ Supported[10]
GCC Supported[11]
Intel C++ Compiler Supported[12]
Microsoft Visual C++ Supported[13]
Pelles C Supported[14]

Notes