Pages

Tuesday, March 11, 2014

Preprocessor to control printf debugging

A fundamental way of debugging an application, especially developed using  C / C++ programming languages is "printf debugging". i.e. To dump a message on to console output with some variables.

However, including too many "printf debugging" statements can hinder the performance of an application. Therefore, it is important to include a mechanism to automatically remove all such debugging statements. The easiest way to achieve this is through conditional compilations.

One straight forward way is to wrap the printf statements within a preprocessor directive as follows.


#ifdef _DEBUG
    printf("Debug message\n");
#endif


This approach adds too much clutter into the source code. Therefore, I was looking for a elegant solution to this fundamental problem and came across the following code block.
 
#ifdef _DEBUG
    #define  DEBUG_MSG printf
#else
    #define  DEBUG_MSG(...) {}
#endif

//To include a debug line
DEBUG_MSG("Sum %i\n", sum);


When _DEBUG is defined, the preprocessor replaces all DEBUG_MSG code with printf. The absence of _DEBUG results in DEBUG_MSGs getting replaced by an empty block. Hence, the printf debugging statement disappears completely from the compiled code. Since this decision is made during compile time, it does not add any additional burden at run time.

No comments:

Post a Comment