65.9K
CodeProject is changing. Read more.
Home

Preprocessor to Control printf Debugging

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 1, 2015

CPOL
viewsIcon

6909

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 onto 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 an 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.