From Electron Cloud
Revision as of 19:23, 2 September 2010 by Ecloud (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Put this in a common header file:

// #define DEBUG_PRINT_ENABLED 1  // uncomment to enable DEBUG statements
#if DEBUG_PRINT_ENABLED
#define DEBUG printf
#else
#define DEBUG(format, args...) ((void)0)
#endif

Then you can use DEBUG just like printf, and the preprocessor will make those statements disappear so that they don't take up any space in the final program (not even the string constants) when you turn it off.

varargs in macros is a newish (or gnu-ish?) thing, so it may not work on all compilers. But very handy when it does work.

Now suppose you need to direct the output somewhere else, e.g. to a logfile, or across a serial link in an embedded system. Put this in the header:

// #define DEBUG_PRINT_ENABLED 1  // uncomment to enable DEBUG statements
#define DEBUG_MAX_LINE_LEN 40

void log_printf(const char* msg, ...);

#if DEBUG_PRINT_ENABLED
#define DEBUG log_printf
#else
#define DEBUG(format, args...) ((void)0)
#endif

and this implementation in one of the .c files:

#include <stdarg.h>

void log_printf(const char* msg, ...)
{
    if (msg)
    {
        char buf[DEBUG_MAX_LINE_LEN + 1];
        va_list argp;
        va_start(argp, msg);
        vsnprintf(buf, DEBUG_MAX_LINE_LEN, msg, argp);
        va_end(argp);
        // TODO write it to the log file or whatever
    }
}