Search code examples
ccompiler-flags

Using if clause instead of processor #ifdef


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)) {

}

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) ...