Search code examples
cprintingmacrosc-preprocessorpragma

Preprocessor message containing macro


How can I print a message containing macros during preprocessing?

E.g.:

#define MACRO_1  1
#pragma message ("Date:" __DATE__)           // OK
#pragma message ("MACRO_1 = " MACRO_1)       // error: pragma message requires parenthesized string

Solution

  • What you should do is to stringize the preprocessor MACRO_1 after being expanded. You can not insert #MACRO_1 into #pragma message() as strays are forbidden. In that case, what the preprocessor is seeing inside #pragma message() is "#MACRO_1" and not "1". However, when you use SSTRINGIZE(x) (as shown in the example below) you are instructing the preprocessor to expand MACRO_1 (get its value which is 1 in your case) and then stringize it (covert it into string). Finally, you will obtain the string "1" inside #pragma message() at the end.

    Please try this code, it should print what you intend to do.

    #define MACRO_1  1
    #pragma message ("Date:" __DATE__)           
    #define STRINGIZE(x) "MACRO_1 = " #x
    #define SSTRINGIZE(x) STRINGIZE(x)
    #pragma message (SSTRINGIZE(MACRO_1))