【问题标题】:Print numeric value of a define that's based on other macros via pragma message?通过编译指示消息打印基于其他宏的定义的数值?
【发布时间】:2015-11-30 01:45:41
【问题描述】:

这类似于How do I show the value of a #define at compile-time?。 Chris Barry 的回答对我不起作用:

#ifdef __GNUC__
    #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
...

#define XSTR(x) STR(x)
#define STR(x) #x
#pragma message "The value of GCC_VERSION: " XSTR(GCC_VERSION)

结果:

$ rm -f dlltest.o && make dlltest.o
g++ -DNDEBUG -g2 -O2 -march=native -pipe -c dlltest.cpp
dlltest.cpp:13:80: note: #pragma message: The value of GCC_VERSION: (4 * 10000 + 9 * 100 + 3)
 #pragma message "The value of GCC_VERSION: " XSTR(GCC_VERSION)
                                                                                ^
dlltest.cpp:12:17: note: in definition of macro ‘STR’
 #define STR(x) #x
                 ^
dlltest.cpp:13:55: note: in expansion of macro ‘XSTR’
 #pragma message "The value of GCC_VERSION: " XSTR(GCC_VERSION)

从上面可以看出,数值没有被打印出来。此外,还打印了很多多余的无用草料。

如何让 GCC 打印基于其他宏的定义的数值?

【问题讨论】:

  • Boost 有一些宏 (BOOST_PP_ADD, BOOST_PP_MUL) 用于 PP 时间数学。但是,数字系统类似于 [0, 255]。
  • @Chris - 我没有使用 Boost。

标签: c++ macros c-preprocessor pragma


【解决方案1】:

预处理器不进行算术替换。 (在#if 中,它可以计算真/假结果,但不幸的是,这是预处理器进行计算的唯一地方。)

boost 预处理器库通过对算术运算使用大量可能参数的枚举来解决此问题,但它仅限于对(非常)小的整数进行运算。它很聪明,但不可扩展。

所以你最好使用字符串连接而不是算术。

#pragma message "GCC version: " XSTR(__GNUC__.__GNUC_MINOR__.__GNUC_PATCHLEVEL__)

不幸的是,gcc 不仅会产生消息,还会产生原始源代码行的回显。使用_Pragma 功能将整个内容包装在一个宏中可能会更好,这样回显的源代码行只包含一个单词:

#define STR(x) #x
#define XSTR(x) STR(x)
#define MSG(x) _Pragma (STR(message (x)))
#define DISPLAY_GCC_VERSION \
  MSG("GCC version: " XSTR(__GNUC__.__GNUC_MINOR__.__GNUC_PATCHLEVEL__))

DISPLAY_GCC_VERSION

【讨论】:

    猜你喜欢
    • 2011-03-03
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 2013-06-14
    • 2023-01-11
    • 2017-12-04
    • 1970-01-01
    相关资源
    最近更新 更多