0

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?

gurkensaas
  • 793
  • 1
  • 5
  • 29
  • It's not possible to concatenate `" string "` with `N`. But why use a string? Just `#error N is supposed ...`. Also note, you are asking XY question. You are _not_ asking how to display the value of N in `#error` message. You are specifically asking about concatenating strings in `#error`. Did you research similar questions? https://stackoverflow.com/questions/27635947/gcc-macro-expansion-of-error https://stackoverflow.com/questions/12637392/c-preprocessor-expand-macro-in-a-warning – KamilCuk Aug 18 '22 at 22:31
  • @KamilCuk Is it possible to get a `#error` to report anything other than the literal characters until the next newline? – gurkensaas Aug 18 '22 at 22:32
  • 1
    I believe there are some serious gymnastics you can do to achieve this, but it's ugly. This seems mostly on point: https://stackoverflow.com/questions/6002594/is-there-a-way-to-have-the-c-preprocessor-resolve-macros-in-an-error-statement – Steve Friedl Aug 18 '22 at 22:34

1 Answers1

1

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
0___________
  • 60,014
  • 4
  • 34
  • 74