C preprocessor: expand macro in a #warning

前端 未结 4 1653
礼貌的吻别
礼貌的吻别 2020-12-12 20:39

I would like to print a macro value (expand the macro) in the #warning directive.

For example, for the code:

#define AAA 17
#warning AAA = ???
         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-12 21:24

    I wouldn't recommend using #warning, since it is not standard C. Besides, what is there that you want to warn against but not throw an error against? Warnings is typically something the compiler uses when you are doing something that is suspicious our outright dangerous, yet allowed by the C standard. You have no such case in normal application, you are going to want it to either compile flawlessly or not at all. Therefore I'd use standard #error and not non-standard #warning.

    You can't type the actual contents of the pre-processor definition. Something like this might suffice:

    #if (AAA < SOMETHING) && (AAA > SOMETHING_ELSE)
      #error AAA is bad.
    #endif
    

    I think this is detailed enough for the programmer. However, if you really want more details and you have a modern C compiler, you can use static_assert. Then you can achieve something close to what you want:

    #include 
    
    #define xstr(s) str(s)
    #define str(s) #s
    #define err_msg(x) #x " is " xstr(x)
    
    #define AAA 17
    
    static_assert(AAA != 17, err_msg(AAA));
    

    this macro mess should print AAA is 17. An explanation over how these macros work can be found here.

    I'm not sure whether static_assert was included in C99 or C11, it is certainly in C11. You might have to use some GCC extension to enable it.

提交回复
热议问题