A c++ project organization trick

This is something that I'm sure many other people have done before but I think it's worth posting up here in case anyone hasn't seen this trick before.

Say you have a situation where you have an automated build process and you have a Debug build and a Production build. Sometimes you want to start working on something that just cannot make it into production. You might find it extremely valuable to keep working on the code and compiling it even if those compiled versions will never end up being released. I like using the following approach if I need to ensure that certain things don't make it through to release.

Say that you have a Makefile based approach [1] to the build you can specify a preprocessor directive from the command line that defines a DEBUG symbol:

DEBUG ?= 0
all: dependencies
ifeq($(DEBUG),0)
    $(CC) -DDEBUG ...
else
    $(CC) ...
endif

Then in your code you can do the following:

#ifndef DEBUG
static_assert(false, "not implemented");
#endif

#ifndef DEBUG
static_assert(false, "not unit tested");
#endif

You can also use #error if you don't have static_assert, however you can't check the logic for templates or constexpr based with the #error approach.

When you then build the project with:

make all

Anything that was marked as needing the DEBUG symbol defined will now throw a static assertion if you try to build it in a non-debug mode. [2] To build those things requires:

make DEBUG=1
[1]this general approach will work with any other build system that you can specify command line arguments to your c++ compiler.
[2]Perhaps calling it DEVELOPMENT would make more sense. After all it's just getting the compiler to remind you to not compile incomplete things into release.

blogroll

social