Print numeric value of a define that's based on other macros via pragma message?

大憨熊 提交于 2019-12-10 19:46:42

问题


This is similar to How do I show the value of a #define at compile-time?. Chris Barry's answer is not working for me:

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

Results in:

$ 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)

As can bee seen above, the numeric value was not printed. In addition, a lot of extra useless fodder was printed.

How can I have GCC print the numeric value of a define that's based on other macros?


回答1:


The preprocessor doesn't do arithmetic substitutions. (In a #if, it can compute a true/false result, but unfortunately that's the only place where the preprocessor does computations.)

The boost preprocessor library works around this by using massive enumerations of possible arguments to arithmetic operations, but it is límited to operations on (very) small integers. It's clever but not scalable.

So you are better off using string concatenation than arithmetic.

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

Unfortunately, gcc will not only produce the message, but also an echo of the original source line. It might be better to wrap the whole thing in a macro, using the _Pragma feature, so that the echoed source line consists only of a single word:

#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


来源:https://stackoverflow.com/questions/32388928/print-numeric-value-of-a-define-thats-based-on-other-macros-via-pragma-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!