Is there a way to have the C Preprocessor resolve macros in an #error statement?

喜欢而已 提交于 2019-12-04 01:29:30

For completeness the C++0x way I suggested (using the same trick as Kirill):

#define STRING2(x) #x
#define STRING(x) STRING2(x)

#define EXPECT(v,a) static_assert((v)==(a), "Expecting " #v "==" STRING(a) " [" #v ": "  STRING(v) "]")


#define VALUE 1

EXPECT(VALUE, 0);

Gives:

g++ -Wall -Wextra -std=c++0x test.cc                     
test.cc:9: error: static assertion failed: "Expecting VALUE==0 [VALUE: 1]"

In Visual Studio you can use pragmamessage as follows:

#define STRING2(x) #x
#define STRING(x) STRING2(x)

#define SOME_MACRO 1

#if SOME_MACRO != 0
    #pragma message ( "SOME_MACRO was not 0; it was " STRING(SOME_MACRO) )
    #error SOME_MACRO was not 0;
#endif

This will generate two messages, but you'll get the value of SOME_MACRO. In G++ use the following instead (from comments: g++ version 4.3.4 works well with parenthesis as in the code above):

#pragma message "SOME_MACRO was not 0; it was " STRING(SOME_MACRO)
#define INVALID_MACRO_VALUE2(x) <invalid_macro_value_##x>
#define INVALID_MACRO_VALUE(x) INVALID_MACRO_VALUE2(x)

#if SOME_MACRO != 0
  #include INVALID_MACRO_VALUE(SOME_MACRO)
#endif

generates "Cannot open include file: 'invalid_macro_value_1': No such file or directory" in Visual Studio 2005 and probably similar messages on other compilers.

This doesn't answer your question directly about using #error, but the result is similar.

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