包含#pragma的宏定义 [英] macro definition containing #pragma

查看:67
本文介绍了包含#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

但是我在Linux上收到以下错误-

But i get 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 statment

如何定义包含#的宏?

解决方案更新:

如该线程中所述定义宏中的编译是:

#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

推荐答案

如何定义包含#的宏?

How can i define a macro that contains a #?

您不能(定义一个包含指令的宏,即.#仍可在宏中用于字符串化,并在##中用于令牌串联).这就是在C99中发明和标准化 _Pragma 的原因.至于C ++,肯定是在C ++ 11标准中,大概是在后来的标准中.

You can't (define a macro that contains a directive, that is. # can still be used in macros for stringization and as ## for token concatenation). That's why _Pragma was invented and standardized in C99. As for C++, it's definitely in the C++11 standard and presumably the later ones.

您可以按以下方式使用它:

You can use it as follows:

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

有了

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

预处理为

# 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"

如您所见, _Pragma 扩展为 #pragma 指令.由于 _Pragma 是标准的,因此,如果Microsoft支持,您应该可以在这里避免 #ifdef .

As you can see, the _Pragmas are expanding to #pragma directives. Since _Pragma is standard, you should be able to avoid the #ifdef here if Microsoft supports it.

这篇关于包含#pragma的宏定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆