CodeProject
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_MSG
s 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.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.