38

Possible Duplicate:
#pragma - help understanding

I saw the pragma many times,but always confused, anyone knows what it does?Is it windows only?

Community
  • 1
  • 1
wireshark
  • 1,145
  • 2
  • 13
  • 19

4 Answers4

48

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 improved compile speed.

See the Wikipedia article for further details.

helpermethod
  • 55,449
  • 64
  • 175
  • 266
  • What does `pragma` mean?I can never remember it... – wireshark Apr 25 '11 at 09:19
  • 2
    @wireshark it's a Greek word, "πράγμα" and it comes from pragmatic as said [here](http://stackoverflow.com/questions/3791259/where-does-the-word-pragma-come-from)....Because the exact meaning in Greek is "thing", but if you focus on where it came from, you can say it means "action". – gsamaras Jul 20 '16 at 18:41
42

It's used to replace the following preprocessor code:

#ifndef _MYHEADER_H_
#define _MYHEADER_H_
...
#endif

A good convention is adding both to support legacy compilers (which is rare tho):

#pragma once
#ifndef _MYHEADER_H_
#define _MYHEADER_H_
...
#endif

So if #pragma once fails the old method will still work.

Alex Kremer
  • 1,638
  • 14
  • 18
4

Generally, the #pragma directives are intended for implementing compiler-specific preprocessor instructions. They are not standardized, so you shouldn't rely on them too heavily.

In this case, #pragma once's purpose is to replace the include guards that you use in header files to avoid multiple inclusion. It works a little faster on the compilers that support it, so it may reduce the compilation time on large projects with a lot of header files that are #include'ed frequently.

2

pragma is a directive to the preprocessor. It is usually used to provide some additional control during the compilation. For example do not include the same header file code. There is a lot of different directives. The answer depends on what follows the pragma word.

danny_23
  • 493
  • 3
  • 14