Search code examples
cc-preprocessorstring-concatenation

Concatenate string in #error preprocessor symbol


I'm trying to do some preprocessor magic. It all works great, except for the error-reporting:

#define N 10
#if N != 9
    #error "N is supposed to be 9, got "N" instead"
    #error "N is supposed to be 9, got " ## N ## " instead"
#endif

Instead of getting the desired output N is supposed to be 9, got 10 instead in either or both cases as a compiler error, I am getting the less desirable

test.c:3:6: error: "N is supposed to be 9, got "N" instead"
    #error "N is supposed to be 9, got "N" instead"
     ^
test.c:4:6: error: "N is supposed to be 9, got " ## N ## " instead"
    #error "N is supposed to be 9, got " ## N ## " instead"
     ^
2 errors generated.

Is there any way to concatenate strings in #error-messages?


Solution

  • You can't do it with #error but it is possible with #pragma message

    #define XSTR(x) #x
    #define STR(x) XSTR(x)
    
    #define N 10
    #if N != 9
    #pragma message "N= " STR(N)
    #error See message above
    #endif