A slightly better debug printf

While I’m familiar with tracing code in a debugger, I still use printf() a lot during debugging. However it’s worth it to make some small improvements.

Introducing this little include file. (Call it debug.h) It has a number of features. For one, you can easily turn on or off debug messages with a single define. So no need to strip out all of your debug messages, only to find out later that you still needed them. Also the compiler has a number of useful defines, like the line number, source file and function that the debug function is called from. So no more searching where that message came from. And it still works exactly the same as a printf(), so you can still pass multiple arguments.


  #include <stdio.h>
  #define debug(x, ...)      do{fprintf(stderr, "%s:%s(%u): " x "\n", __FILE__, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);}while(0)
  #define debug(x, ...)      /* x */


Here is example.c

#include <stdio.h>

#define DEBUG 1
#include "debug.h"

int main()
printf("Hello world!\n");

debug("Hello %s world!", "debug");

return 0;

Compiling is straightforward:

gcc -Wall -o example example.c

And here is the output of our little program. As you can see, it’s already better then plain printf()’s.

Hello world!
example.c:main(11): Hello debug world!

The thing to take away from this though, is to make your own debugging functions. Maybe add some colors or put in some warning levels. Just think of issues you usually run into and see if there are any improvements you can make to save yourself time in the future.

Leave a Comment

Your email address will not be published.