cgccc-preprocessor

Evaluation of defined(x) in a `#pragma message` output string


For debugging purposes, I am trying to output information on whether certain symbols are defined, but without having to impair my code readability with too many #if defined() blocks. I tried using the defined() operator in text output by #pragma message like so:

#pragma message defined(__UNDERLAY__)

I was expecting this to output 1 if __UNDERLAY__ was defined, and 0 if it was not. But instead:

testbed_defines.c:61:9: warning: expected a string after ‘#pragma message’ [-Wpragmas]
   61 | #pragma message defined(__UNDERLAY__)
      |         ^~~~~~~

I tried to "stringify" like this:

#pragma message "" defined(__UNDERLAY__)

This only caused a different error:

testbed_defines.c:61:9: warning: junk at end of ‘#pragma message’ [-Wpragmas]
   61 | #pragma message "" defined(__UNDERLAY__)
      |         ^~~~~~~

I tried the concatenation operator:

testbed_defines.c:61:20: error: stray ‘##’ in program
   61 | #pragma message "" ## defined(__UNDERLAY__)
      |                    ^~
testbed_defines.c:61:9: warning: junk at end of ‘#pragma message’ [-Wpragmas]
   61 | #pragma message "" ## defined(__UNDERLAY__)
      |         ^~~~~~~

Is there a way to actually output the value of defined(x) without having to construct an #if block? Especially as that would need me to write the two valid values (0 and 1) into code like magic numbers. It looks as though defined simply isn't being evaluated here at all!


Solution

  • Is there a way to actually output the value of defined(x) without having to construct an #if block?

    No. defined() is only evaluated inside #if and #elif and such.

    You could check if the macro expands to nothing with https://gustedt.wordpress.com/2010/06/08/detect-empty-macro-arguments/ .

    It is not possible to expand to 1 or 0 depending on if macro is defined Is there any way to convert a variable macro into 0 or 1 based on whether it is defined? .