Pragma once

Pragma once

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"

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.

Some compilers such as GCC 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. [http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC8]

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 GRANDFATHER_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. It also requires less typing than the include guard method.

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 [http://groups.google.com/groups?selm=bvjqhn$q5o$1@news-reader1.wanadoo.fr] [http://groups.google.com/groups?selm=488cbfe1.0304061213.264d94d@posting.google.com] and GCC as of 1998. [http://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC8] 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. [http://gcc.gnu.org/onlinedocs/gcc-4.0.3/cpp/Obsolete-once_002donly-headers.html#Obsolete-once_002donly-headers] [http://gcc.gnu.org/gcc-3.4/changes.html]

You can use both #pragma once and include guards to write portable code that can also take advantage of #pragma once optimizations the compiler may support:

;File "grandfather.h"
#pragma once
#ifndef GRANDFATHER_H
#define GRANDFATHER_H

struct foo { int member;};

#endif /* GRANDFATHER_H */

External links

* [http://msdn2.microsoft.com/en-us/library/d9x1s805(vs.71).aspx "Pragma Directives (C/C++)"] at MSDN
* [http://gcc.gnu.org/onlinedocs/gcc/index.html GCC Pragma and other commands] at [http://gcc.gnu.org/ GNU Org]


Wikimedia Foundation. 2010.

Игры ⚽ Поможем написать реферат

Look at other dictionaries:

  • Pragma once — Saltar a navegación, búsqueda El título de este artículo se muestra incorrectamente debido a limitaciones técnicas. El título correcto es #pragma once. Del Lenguaje de programación C y C++, #pragma once es una directiva de Preprocesador de C no… …   Wikipedia Español

  • Pragma once — Правильный заголовок этой статьи  #pragma once. Он показан некорректно из за технических ограничений. В языках программирования Си и C++ #pragma once  нестандартная, но широко распространенная препроцессорная директива, разработанная… …   Википедия

  • Include Guard — Der Include Guard (dt: Include Wächter) ist eine Programmiertechnik, um in C oder C++ das Problem der doppelten Einbindung (engl.: double inclusion) zu umgehen. Dieses Problem tritt auf, wenn innerhalb eines Moduls mehrfach die gleiche Header… …   Deutsch Wikipedia

  • C preprocessor — The C preprocessor (cpp) is the preprocessor for the C and C++ computer programming languages. The preprocessor handles directives for source file inclusion (#include), macro definitions (#define), and conditional inclusion (#if). In many C… …   Wikipedia

  • Undefined behavior — In computer programming, undefined behavior is a feature of some programming languages most famously C.[1] In these languages, to simplify the specification and allow some flexibility in implementation, the specification leaves the results of… …   Wikipedia

  • Include guard — In the C and C++ programming languages, an #include guard, sometimes called a macro guard, is a particular construct used to avoid the problem of double inclusion when dealing with the #include directive. The addition of #include guards to a… …   Wikipedia

  • Include guard — Эта статья или раздел нуждается в переработке. Пожалуйста, улучшите статью в соответствии с правилами написания статей …   Википедия

  • Заголовочный файл — (иногда головной файл, англ. header file), или подключаемый файл  в языках программирования файл, механически «вставляемый» компилятором в исходный текст в том месте, где располагается некоторая директива ({$I file.inc} в Паскале,… …   Википедия

  • Препроцессор Си — Препроцессор С/С++  программный инструмент, изменяющий код программы для последующей компиляции и сборки, используемый в языках программирования Си и его потомка C++. Этот препроцессор обеспечивает использование стандартного набора… …   Википедия

  • Header file — In computer programming, particularly in the C and C++ programming languages, a header file or include file is a file, usually in the form of source code, that is automatically included in another source file by the compiler. Typically, header… …   Wikipedia

Share the article and excerpts

Direct link
Do a right-click on the link above
and select “Copy Link”