Wednesday, April 13, 2011

#ifdef DEBUG print statements in C

The #ifdef DEBUG design pattern for debug output is extremely common in C code. Here is a nice DEBUG macro I have used in the past:

#ifdef DEBUG
#define DEBUG_PRINT(fmt, args...)  \
       fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, __LINE__, __FUNCTION__, ##args)
#else
#define DEBUG_PRINT(fmt, args...)    /* Don't do anything in non-debug builds */
#endif

As suggested in this post, letting the compiler see your debug code is important to ensure it isn't broken by people changing code without making debug builds. This macro achieves that goal by letting the preprocessor insert a statement that will be pulled out by the optimiser for non-debug builds. This is the best solution I have come across.

#ifdef DEBUG
#define DEBUG_TEST 1
#else
#define DEBUG_TEST 0
#endif

#define DEBUG_PRINT(fmt, args...) \
        do { if (DEBUG_TEST) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
                                __LINE__, __FUNCTION__, ##args); } while (0)

No comments: