Arvids Blog

Thoughts on programming and more

Stop using #ifdef for configuration

Using #ifdef’s to configure different conditional compilations is very error prone.

I believe we’ve all had the case where something was compiled, while it shouldn’t have been, due to accidentally creating/including a #define of the same name or defining it to 0 while checking with #ifdef.

While I won’t give you a solution to fix the flawed model of using the preprocessor for conditional inclusion, I’ll give you a solution to make it less error prone:

    /* Do something in debug. */
    /* Do something in production. */

The USING macro requires each configuration macro to be explicitly defined to special ON or OFF values, or you’ll get an error1.

By simply defining USING to a mathematical expression and ON / OFF to be the operators, we’ll get an error whenever an undefined or otherwise defined macro is tried to be used as an argument:

#define USING(x) ((1 x 1) == 2)
#define ON +
#define OFF -

Comments, criticism? Drop me a tweet @ArvidGerstmann.


Not entirely correct, but good enough for our case.