tags:

views:

416

answers:

3

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

+2  A: 

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
mipadi
Check variadic macro's syntax
qrdl
I'm pretty sure it's correct. Do you see something wrong?
mipadi
+4  A: 
#ifdef DEBUG
#define DEBUG_PRINT(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false )
#else
#define DEBUG_PRINT(...) do{ } while ( false )
#endif
moonshadow
+1 for `__VA_ARGS__`, but note that's only required to exist in C99 implementations.
pmg
Actually, you don't need the `do { ... } while (0)` idiom around the `fprintf()`
Remo.D
+5  A: 

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.

Aidan Cully