C++ Preprocessor #pragma once


Example

Most, but not all, C++ implementations support the #pragma once directive which ensures the file is only included once within a single compilation. It is not part of any ISO C++ standard. For example:

// Foo.h
#pragma once

class Foo
{
};

While #pragma once avoids some problems associated with include guards, a #pragma - by definition in the standards - is inherently a compiler-specific hook, and will be silently ignored by compilers that don't support it. Projects which use #pragma once must be modified to be standard-compliant.

With some compilers - particularly those that employ precompiled headers - #pragma once can result in a considerable speedup of the compilation process. Similarly, some preprocessors achieve speedup of compilation by tracking which headers have employed include guards. The net benefit, when both #pragma once and include guards are employed, depends on the implementation and can be either an increase or decrease of compilation times.

#pragma once combined with include guards was the recommended layout for header files when writing MFC based applications on windows, and was generated by Visual Studio’s add class, add dialog, add windows wizards. Hence it is very common to find them combined in C++ Windows Applicants.