Debug Print Macro in C?

Viewed 77606

in C, what is the proper way to define a printf like macro that will print only when DEBUG symbol is defined?

#ifdef DEBUG
#define DEBUG_PRINT(???) ???
#else
#define DEBUG_PRINT(???) ???
#endif

where ??? is where I am not sure what to fill in

8 Answers

I've seen this idiom a fair amount:

#ifdef DEBUG
# define DEBUG_PRINT(x) printf x
#else
# define DEBUG_PRINT(x) do {} while (0)
#endif

Use it like:

DEBUG_PRINT(("var1: %d; var2: %d; str: %s\n", var1, var2, str));

The extra parentheses are necessary, because some older C compilers don't support var-args in macros.

#ifdef DEBUG
#define DEBUG_PRINT(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false )
#else
#define DEBUG_PRINT(...) do{ } while ( false )
#endif

Something like:

#ifdef DEBUG
#define DEBUG_PRINT(fmt, args...)    fprintf(stderr, fmt, ## args)
#else
#define DEBUG_PRINT(fmt, args...)    /* Don't do anything in release builds */
#endif

I like this way the best because it wont add any asm instructions to your release build.

#define DEBUG
#ifdef DEBUG
#define  debug_printf(fmt, ...)  printf(fmt, __VA_ARGS__);
#else
#define debug_printf(fmt, ...)    /* Do nothing */
#endif

I see some minor errors in this implementation. So, here is my approach:

#ifdef DEBUG
    #define DEBUG_PRINTF(...) printf("DEBUG: "__VA_ARGS__)
#else
    #define DEBUG_PRINTF(...) do {} while (0)
#endif

Example usage:

DEBUG_PRINTF("hello\n");

Then, if I build and run with the -DDEBUG define on in my C build options, like this:

# Build
gcc -Wall -Wextra -Werror -std=c11 -DDEBUG -o build/my_program \
my_program_tests.c my_program.c

# Run
build/my_program

then I see this output:

DEBUG: hello

But if I build withOUT the -DDEBUG define in my compiler C options, then I see no debug prints whatsoever.

Related