Macro definition containing #pragma

I am trying to define the following macro:

#if defined(_MSC_VER)
    #define PRAGMA_PACK_PUSH(n)  __pragma(pack(push, n))
    #define PRAGMA_PACK_POP()    __pragma(pack(pop))
#else
    #define PRAGMA_PACK_PUSH(n)     #pragma (pack(push, n))
    #define PRAGMA_PACK_POP()       #pragma (pack(pop))
#endif

      

But I am getting the following error on Linux -

 error: '#' is not followed by a macro parameter
  #define PRAGMA_PACK_PUSH(n)  #pragma (pack(push, n))

      

and it points to the first ')' in the status

How do I define a macro containing #?

Solution update:

As stated in this Pragma thread in the macro definition , the syntax that worked was:

#if defined(_MSC_VER)
    #define PRAGMA_PACK_PUSH(n)  __pragma(pack(push, n))
    #define PRAGMA_PACK_POP()    __pragma(pack(pop))
#else
    #define PRAGMA_PACK_PUSH(n)     _Pragma("pack(push, n)")
    #define PRAGMA_PACK_POP()       _Pragma("pack(pop)")
#endif

      

+3


source to share


1 answer


How do I define a macro containing #?

You cannot (define a macro that contains a directive, i.e.. # Can still be used in macros for string and as ## for marker concatenation). This is why it _Pragma

was invented and standardized in C99. As far as C ++ is concerned, this is definitely in the C ++ 11 standard and presumably more recent.

You can use it like this:

#define PRAGMA(X) _Pragma(#X)
#define PRAGMA_PACK_PUSH(n)     PRAGMA(pack(push,n))
#define PRAGMA_PACK_POP()       PRAGMA(pack(pop))

      

Wherein



PRAGMA_PACK_PUSH(1)
struct x{
    int i;
    double d;
};
PRAGMA_PACK_POP()

      

preprocesses on

# 10 "pack.c"
#pragma pack(push,1)
# 10 "pack.c"

struct x{
 int i;
 double d;
};

# 15 "pack.c"
#pragma pack(pop)
# 15 "pack.c"

      

As you can see, they _Pragma

expand to directives #pragma

. Since it _Pragma

is standard, you can avoid #ifdef

here if Microsoft supports it.

+3


source







All Articles