22

What is the difference between #pragma and _Pragma() in C?

syntax:

#pragma arg

and

_Pragma(arg)

When should I use _Pragma(arg)?

msc
  • 33,420
  • 29
  • 119
  • 214
Jayesh
  • 4,755
  • 9
  • 32
  • 62
  • 6
    The C standard provides the `_Pragma` operator as an alternative to `#pragma`. It's likely that `_pragma` is similar but specific to a vendor (Microsoft?). – Jonathan Leffler Aug 03 '17 at 07:38

2 Answers2

25

_Pragma operator introduced in C99. _Pragma(arg) is an operator, much like sizeof or defined, and can be embedded in a macro.

According to cpp.gnu.org reference:

Its syntax is _Pragma (string-literal), where string-literal can be either a normal or wide-character string literal. It is destringized, by replacing all \\ with a single \ and all \" with a ". The result is then processed as if it had appeared as the right hand side of a #pragma directive. For example,

 _Pragma ("GCC dependency \"parse.y\"")

has the same effect as #pragma GCC dependency "parse.y". The same effect could be achieved using macros, for example

 #define DO_PRAGMA(x) _Pragma (#x)
 DO_PRAGMA (GCC dependency "parse.y")

According to IBM tutorial:

The _Pragma operator is an alternative method of specifying #pragma directives. For example, the following two statements are equivalent:

#pragma comment(copyright, "IBM 2010")
_Pragma("comment(copyright, \"IBM 2010\")")

The string IBM 2010 is inserted into the C++ object file when the following code is compiled:

_Pragma("comment(copyright, \"IBM 2010\")")
int main() 
{
   return 0;
}

For more information about _pragma with example.

FeRD
  • 1,699
  • 15
  • 24
msc
  • 33,420
  • 29
  • 119
  • 214
11

From here:

Pragma directives specify machine- or operating-specific compiler features. The __pragma keyword, which is specific to the Microsoft compiler, enables you to code pragma directives within macro definitions.

Also (same link):

The __pragma() Keyword

Microsoft specific

The compiler also supports the __pragma keyword, which has the same functionality as the #pragma directive, but can be used inline in a macro definition. The #pragma directive cannot be used in a macro definition because the compiler interprets the number sign character ('#') in the directive to be the stringizing operator (#).

So basically you can always use #pragma instead of __pragma(). There is no need to use __pragma(), but it can be used sometimes.

Community
  • 1
  • 1
CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 3
    After edits, the OP mentions `_Pragma` which is standard C as per C99. See C17 6.10.9. Unlike `__pragma` which might very well be some MS goo. You might want to update this answer since it doesn't address the syntax used in the question. The original question had `_pragma` which is neither ISO C nor (as far as I know) MS goo. – Lundin Jan 28 '19 at 12:44