Check the value of a macro at runtime
Now I need to check the value of DEF1 or DEF2 at runtime,
It's impossible. The preprocessor macro values are processed even before compilation.
You can convert processor macros to variable values and check the variable values at runtime.
Something in 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"
}
source to share
You mean at compile time, no? Runtime if
is unsigned hashing.
Macro expressions for #if
are evaluated as integers and w90> macros silently default to zero.
I'm not sure what you want to achieve, but if the values of your macros are defined in source, before you include 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 performed 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 can lead to surprises.
source to share
The macro is expanded by the preprocessor into regular C source code and then used the same way. For example, if you have a macro MY_NUMBER
that must be #define
d for a number, you can check its value at runtime, just as you would with any other number.
if (MY_NUMBER == 42)
printf("MY_NUMBER is 42\n");
else
printf("MY_NUMBER is not 42 but rather %d\n", MY_NUMBER);
However, if your macro expands to nasty things and you would like to check that text, you will have to convert the macro to a string and then look at that string. For example:
if (strcmp(STRINGIZE(MY_MACRO), "for (;;)") == 0)
printf("MY_MACRO was #define'd to an infinite loop.");
A common trick for "planing" a macro looks like this if you haven't seen it before.
#define STRINGIZE_R(X) #X
#define STRINGIZE(X) STRINGIZE_R(X)
source to share