Monday, May 31, 2010

The _Pragma Operator

You cannot construct a #pragma directive (or any other preprocessor directive) by means of a macro expansion. For cases where you would want to do that, C99 has also introduced the preprocessor operator _Pragma, which you can use with macros. Its syntax is as follows:

_Pragma ( string_literal )

Here is how the _Pragma operator works. First, the string_literal operand is "de-stringized," or converted into a sequence of preprocessor tokens, in this way: the quotation marks enclosing the string are removed; each sequence of a backslash followed by a double quotation mark (\") is replaced by a quotation mark alone ("); and each sequence of two backslash characters (\\) is replaced with a single backslash (\). Then the preprocessor interprets the resulting sequence of tokens as if it were the text of a #pragma directive.

The following line defines a helper macro, STR, which you can use to rewrite any #pragma directive using the _Pragma operator:

#define STR(s) #s // This # is the "stringify" operator.

With this definition, the following two lines are equivalent:

#pragma tokens

_Pragma ( STR(tokens) )

The following example uses the _Pragma operator in a macro:

#define ALIGNMENT(n) _Pragma( STR(pack(n)) )

ALIGNMENT(2)

Macro replacement changes the ALIGNMENT(2) macro call to the following:

_Pragma( "pack(2)" )

The preprocessor then processes the line as it would the following directive:

#pragma pack(2)

Source: C in a Nutshell - O'Reilly Media

No comments:

Post a Comment