Suppose I pass a macro defs via -D
during compilation:
% gcc -DDEF1=ABC -DDEF2=DEF ...
Now, I need to check the value of DEF1 or DEF2 in a runtime, however this doesn't work:
#if DEF1==ABC
...
#else
...
#endif
What am I doing wrong? Is it possible to achieve what I need? Thanks.
Now, I need to check the value of DEF1 or DEF2 in a runtime,
That is not possible. The values of preprocessor macros are processed even before compile time.
You can convert the processor macros to values of variables and check the values of the variables at run time.
Something along the following lines should work.
#define STR2(x) #x
#define STR(X) STR2(X)
char const* str = STR(DEF1);
if ( strcmp(str, "ABC") == 0 )
{
// Process "ABC"
}
else if strcmp(str, "DEF") == 0 )
{
// Process "DEF"
}
You mean at compile time, no? The run-time if
is the one without the hash sign.
Macro expressions for #if
are evaluated as integers and undefined macro expressions silently default to zero.
I'm not sure what you want to accomplish, but if the values of your macros are defined in the source before you switch on them with #if
, you can do something like this:
#define APPLE 1
#define ORANGE 2
#define PEAR 3
#if FRUIT==APPLE
const char *fname = "Apple";
#elif FRUIT==PEAR
const char *fname = "Pear";
#elif FRUIT==ORANGE
const char *fname = "Orange";
#else
#error "Must specify a valid FRUIT"
#endif
Of course, the selection will also be done when your macro is the numeric value of one of the possible values or another macro that happens to expand to the same value, which might lead to surprises.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With