Conditional printf debug statements in C based programming languages

One of the first things people learn to do when learning to program is how to write an ‘Hello World’ application. For many programming languages this involves writing the iconic sentence to a console window. Its amazing how the same fundamental concepts from the ‘Hello World’ application can extend into hardcore application debugging. At university we called this ‘printf debugging’. However in the real world, its important to remember that having too many unnecessary logging statements in production applications can impact performance. In compiled programming languages there are ways to automatically remove all ‘printf debugging’ statements. Here is how to do it on C, C++ and Objective C…

Start by placing the following in a h/hh file and #import “…” the file into the appropriate files or include it in the prefix header.

#ifdef DEBUG
// Update the following if needed…
#define DEBUGLOG(ARGS…) printf(ARGS)
#else
#define DEBUGLOG(ARGS…) do {} while (0)
#endif

The next step is to setup the compiler by adding the following in debug builds…

-DDEBUG

Also, you might want to enable optimizations on the flag when compiling a release build…

-0s

And your done! Heres how you would use it…

DEBUGLOG(“Hello world”);

One thought on “Conditional printf debug statements in C based programming languages

  1. Random note, rather than just using Debug, most real apps use levels of logging e.g debug (1) , info (2), error (3). This helps to filter out the info you need e.g. devs are interested in debug, but production apps could be slowed down with too much debug info and hence only log errors. App testers are interested in info to verify if the right steps have been executed.

    /shitididnotlearninuni

Leave a Reply