Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check a macro value in run-time

Tags:

c

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.

like image 767
Mark Avatar asked Sep 13 '25 22:09

Mark


2 Answers

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"
}
like image 69
R Sahu Avatar answered Sep 15 '25 12:09

R Sahu


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.

like image 26
M Oehm Avatar answered Sep 15 '25 13:09

M Oehm