Bobby Anguelov's Blog

A day in the life of a wannabe game developer

Some C++ Debugging Advice – use #ifdef

If you are an experienced c++ programmer you can stop reading, nothing I cover here will be of any use to you. I’m just writing a little post on a simple little preprocessor trick that c++ programmers have been using for years. Using the #ifdef directive to tag blocks of debugging code.

So lets we have a function that does something like searching through a tree, while debugging we’d like to lets say have a counter to count all the nodes visited during the search but of course in the released version we don’t need this counter using up precious resources. lets have some example code:

double counter;

void treeSearch::visitNode(node* n)
{
	... some code ...
	counter++;
}

Some beginner programmers would probably do this:

bool debugMode = false;
double counter;

void treeSearch::visitNode(node* n)
{
	... some code ...
	if ( debugMode) counter++;
}

Yeh, that works but now every time you visit a node, the program evaluates an if statement, not to mention the memory for the counter has still been allocated. Yes in this case memory cost is pretty negligible but that is not always the case. So how can we improve upon this? The answer is by using basic pre-processor directives, more specifically conditional inclusions (#ifdef). Simply put these directives mark code for inclusion into the program during compile time if some condition is met.

so our code would now look as follows:

#ifdef _DEBUG
double counter;
#endif

void treeSearch::visitNode(node* n)
{
	... some code ...
	#ifdef _DEBUG
	counter++;
	#endif
}

So now those lines will only be included if _DEBUG is defined, what this means is that the counter variable and the code that increments it doesnt get compiled, and your program is as fast as possible and still has debugging functions. You can set the _DEBUG flag in your code manually by using the define directive: #define _DEBUG, or if your IDE supports it, multiple compile profiles, one of which defines _DEBUG before compiling. Visual studio by default defines _DEBUG when compiling using the Debug profile.

So that was a very simple and brief tutorial on something pretty much most C++ programmers know, but i posted it just in case some didnt :)

27 April 2009 Posted by Bobby | Programming | | 1 Comment