Wednesday, September 26, 2007

#ifdef _DEBUG - baaaad directive!

I see a lot of code that uses _DEBUG or NDEBUG to create different versions of functions, variables, etc:

#ifdef _DEBUG
void myfunc(my_args);
void myfunc(my_args);

However, we can always do better - when using #ifdef, specify your intent. The fact that a directive happens to be turned on only in debug mode, that's a different story.

Why? You have more flexibility, being able to turn the directive on/off in both debug and release configurations, or even in other custom configuration you might have.

Case in point:


// even on a failed assertion, we don't break!
#undef assert
#define assert(exp) (void)( (exp) || (custom_assert(#exp, __FILE__, __LINE__), 0) )
void custom_assert(const char *, const char *, unsigned);

The above allows me to create my custom assert function. This will happen only if CUSTOM_ASSERT is turned on.

For my application , I need this:
  • in release, while doing testing
  • in debug mode, while deploying application to the customer


Thiago Delgado Pinto said...

See a good discussion about this at

Michael Spencer said...

Good idea. I saw this all over boost but never thought to apply it to my own code. Thanks!

BTW, do you think it would be better to place an "if debug, FEATURE_ON" someplace central in the code (like configuration.h)? Or to define it in the makefile/project file? Personally I would use the configuration.h, but allow any define in the makefile/project to override it (although that would require both FEATURE_ON and FEATURE_OFF).