Coding,  Random,  Ubuntu

Hacks They Don’t Teach in School… (#1)

I thought it would be interesting to do a series on Hacks they don’t teach you in university. I’ve thought of quite a few. I like thinking about this, stirs my memories to back when I was just fledging.

Today, we’re going to talk about…

Debug #define dumps

Debuggers like gdb are great, but sometimes you need logging or debugging, and the ability to turn it on and off when you need it.

I learned this trick from my coworker Eric P. (creator of Handbrake) back when I was an intern. Obviously, this isn’t a secret, but its something you’ve got to learn at some point if you’re a C coder…

This trick is simple and versatile. Put something like this is your project header:

 #define DEBUG_ON 1
#define PRINT(...)      printf(__VA_ARGS__)
#define PRINT(...)

Then, anywhere in your program, you can do:

PRINT("this is a test messagen")

and it will work like a printf, that you can turn off and on by editing the DEBUG_ON define (or even a gcc -D DEBUG_ON will compile the debug messages into the code)

This might seem trivial, but you can edit hundreds of debug log messages out of your code very quickly, and saves a lot of time. Plus, since this is in the preprocessor, the printf’s are not compiled into the code, saving your code from having to do a conditional check at every instance of a print during run time! If you really want to get fancy, you can add different levels of debug logging for different statements, or use stderr instead of stdout. Play around!

Its faster, and cleaner, and is a good trick for someone just starting out in C/C++ to know!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.