Click here to Skip to main content
15,885,767 members
Articles / All Topics
Technical Blog

Preprocessor to Control printf Debugging

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
1 Nov 2015CPOL 6.6K   1   1
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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Engineer MTT Network (Pvt.) Ltd.
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Suggestiona bit better Pin
John Torjo2-Nov-15 10:48
professionalJohn Torjo2-Nov-15 10:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.