【问题标题】:How can I define a macro using other preprocessor directives?如何使用其他预处理器指令定义宏?
【发布时间】:2020-02-19 18:32:24
【问题描述】:

我正在尝试定义以下宏来禁用特定警告:

#define HUGE_VAL_DISABLE_WRN #pragma warning( disable : 4005 )

HUGE_VAL_DISABLE_WRN    // <-- errors here
#include "header.h"

我收到以下错误(都在同一行):

error C2121: '#' : invalid character : possibly the result of a macro expansion
error C2146: syntax error : missing ';' before identifier 'warning'
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2065: 'disable' : undeclared identifier
error C2143: syntax error : missing ')' before ':'
error C2448: 'warning' : function-style initializer appears to be a function definition
error C2059: syntax error : 'constant'
error C2059: syntax error : ')'

我想做的是定义一个包含一些预处理器指令的宏,在某些情况下它可以是空的,但我显然遗漏了一些东西。

完整的定义是:

#if (_MSC_VER < REC_VISUAL_CPP_VERS && INTEL_MKL_VERSION < REC_INTEL_MKL_VERS)
#define HUGE_VAL_DISABLE_WRN_BEGIN \
    _Pragma("warning( push )") \
    _Pragma("warning( disable : 4005 )") // macro redefinition
#define HUGE_VAL_DISABLE_WRN_END #pragma warning( pop )
#else
    #define HUGE_VAL_DISABLE_WRN_BEGIN
    #define HUGE_VAL_DISABLE_WRN_END
#endif

从这里我得到:

error : this declaration has no storage class or type specifier
error : a value of type "const char *" cannot be used to initialize an entity of type "int"
error : expected a ";"
warning : parsing restarts here after previous syntax error

【问题讨论】:

  • 您已经在使用_Pragma 来生成前两个编译指示。所以也用它来生成第三个。 Pragma in define macro

标签: visual-c++ macros c-preprocessor pragma


【解决方案1】:

我刚刚发现 Microsoft Visual C++(至少到 2019 版)不提供 _Pragma 关键字(标准 C++11 的一部分)。

他们有自己的,略有不同的__pragma关键字:

#define HUGE_VAL_DISABLE_WRN_BEGIN \
    __pragma(warning( push )) \
    __pragma(warning( disable : 4005 )) // macro redefinition

【讨论】:

    猜你喜欢
    • 2021-12-29
    • 1970-01-01
    • 2021-07-19
    • 2011-02-12
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2022-01-01
    相关资源
    最近更新 更多