Kalpana Kalpana (Editor)

Pragma once

Updated on
Edit
Like
Comment
Share on FacebookTweet on TwitterShare on LinkedInShare on Reddit

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, avoidance of name clashes, and sometimes improvement in compilation speed.

Contents

Example

File "grandparent.h"
File "parent.h"
File "child.c"

Advantages

The most common alternative to #pragma once is to use #define to set an include guard macro, the name of which is picked by the programmer to be unique to that file. For example,

This is more complicated, possibly less efficient, and prone to error as there are no mechanisms to prevent a programmer accidentally using the same macro name in more than one file, which would result in only one of the files being included. This problem renders #pragma once to be advantageous. Since the compiler itself is responsible for handling #pragma once, the programmer cannot make errors which cause name clashes.

Using #pragma once instead of include guards will, for some compilers, improve 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. It is important to note that some compilers such as GCC, Clang, and EDG-based compilers include specific optimizations to recognize and optimize the handling of include guards, and thus little or no speedup benefit is obtained from the use of #pragma once.

Caveats

Identifying the same file on a file system is not a trivial task. Symbolic links and especially hard links may cause the same file to be found under different names in different directories. Compilers may use a heuristic that compares file size, modification time and content. This backfires when the same file is intentionally copied into several parts of a project. With include guard based on file path these copies would be treated differently while #pragma once may arbitrarily treat them as the same file in a compiler-dependent way.

Portability


C/C++ Preprocessor Detector:


Usage:

References

Pragma once Wikipedia