Search code examples
c++compilationc-preprocessorconditional-compilation

Are there any options other than using #define for conditional compilation?


I want to use conditional compilation for testing different properties of my code; however, I don't want to pollute the global namespace. Would someone be kind enough to let me know if there is a way to use conditional compilation without using #define?

I have searched for an option, but most of the other posts refer to the usage of static const, etc to choose different code during run-time. I, however, want to compile a different code. For example, instead of:

#define A_HASH_DEFINE
...
#ifdef A_HASH_DEFINE
 Some code
#elif ANOTHER_HASH_DEFINE
 Some other code
#endif

I would like to be able to use something with a scope, such as:

scope::A_SCOPED_HASH_DEFINE
...
#ifdef scope::A_SCOPED_HASH_DEFINE
 Some code
#elif scope::ANOTHER_SCOPED_HASH_DEFINE
 Some other code
#endif

Solution

  • If you're using C++17, you should use if constexpr.

    It is essentially an if statement where the branch is chosen at compile-time, and any not-taken branches are discarded. It is cleaner than having the #ifdefs splattered throughout your code.

    #ifdef _DEBUG
    constexpr bool debug_mode = true;
    #else
    constexpr bool debug_mode = false;
    #endif
    
    if constexpr (debug_mode) {
       //debug code
    }
    

    You can read more about how it replaces #if … #else in FooNathan's blog:

    The year is 2017 - Is the preprocessor still needed in C++?