Question

I am using a #ifdef block to conditionally include a block of code based on -Dflag passed to the compiler.

Is there a way to implement this with an if?

Something along the lines of:

if (defined(flag)) {

}
Was it helpful?

Solution

You use preprocessor to produce a different flag, which could be tested with a run-time if statement, like this:

#ifdef flag
#define flag_defined 1
#else
#define flag_defined 0
#endif

Now you can do this:

if (flag_defined) ...

OTHER TIPS

If you define a macro so that it evaluates to either zero or nonzero, then you can use it in the condition of the if statement. Since it's a compile-time constant, in case it's zero, the dead code eliminator pass in the compiler will remove the unreachable code anyway.

If you are willing to give flag a value (0 or 1) instead of defining it or not, you can do

cc -Dflag=1 file.c

with

if (flag) { ... }

without messing up your code with ugly #ifdefs. You are also protected against forgetting to define flag at all: in this case your compiler treats flag as an identifier. Since you never declared it, you'll get a compile time error about an undeclared or undefined symbol flag.

No, you can't use a C if statement to check if a preprocessor token is defined. You can use one of these forms though

#ifdef flag
...
#endif

#if defined(flag)
...
#endif

You can however check if the token evaluates to a true/false C expression,

if you use -Dflag=1 you can do

if (flag) {
  ...
}

And if you want to turn it off, you can define the macro as -Dflag=0

Following this you can define a new preprocessor token that you can check with a C if statement. e.g.

#ifdef flag
#define FLAG_SET 1
#else
#define FLAG_SET 0
#endif

if(FLAG_SET) { //the flag macro was defined
...
}

If all you want to do is is check whether the flag is defined, there's no point to all of this, just use #ifdef. With a C if statement, the most C compilers will optimize away the code, there's nothing you could change at runtime to get any benefit of not using the preprocessor.

#ifdef FLAG
#define FLAG_VALUE 1
#else
#define FLAG_VALUE 0
#endif

int flag = FLAG_VALUE;

...

if(flag)
{
    ....
}

Alternatively just use -DFLAG_VALUE=1 or -DFLAG_VALUE=0 as appropriate and use FLAG_VALUE directly.

If you plan on being able to change the FLAG_VALUE at runtime you will need a variable. If you change in non-obvious ways (e.g. via a debugger or through other loader trickery) make sure to declare it volatile, otherwise the compiler might be able to do dead-code elimination and remove huge chunks of code.

Also, if you don't plan on changing the value of flag after initializing, then you should probably make it const.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top