This is code for the C99 standard (gcc on linux).
What I'm trying to do: Write a macro like DEBUG ("some message") that I can drop into code and will only be compiled in if DEBUG_WANTED (or whatever) is defined. Sounds simple, but...
I have some time-sensitive code that is very tricky. As I debug it, I've put in commands like this:
The debug() function is a straightforward vfprintf() routine (that works fine) and debug_wanted is a global variable set at run-time as a command-line option.Code:debug ("At step three, branching to step %i\n",next_step);
However, having all these debug() calls all over the place slows down the code when I no longer need debugging. So I could either remove all the debug() calls when I no longer need them (and then hope I never need to go put them back in), or change them to conditionally compiled code. Then I can chose to compile with debug support on or off.
I like the latter idea, but am struggling to write the macro. I don't want to have to do something like this for each call (there are perhaps 100 debug() lines ;-)
I would prefer something like this:Code:#ifdef DEBUG debug ("At step three, branching to step %i\n",next_step); #endif
The DEBUG() macro would be like this:Code:DEBUG("At step three, branching to step %i\n",next_step);
...except that doesn't work ;-)Code:#define DEBUG(msg...) \ #ifdef DEBUG_WANTED \ debug (msg) \ #endif
I just can't figure out what I'm doing wrong in nesting the preprocessor directives...anyone have a spare clue?
I'm getting a compiler error that says "'#' is not followed by a macro parameter". I suspect it's not possible to nest preprocessor directives in this way...
Or is there another way to accomplish this without #ifdef DEBUG_WANTED before every call to a debug printer?
(BTW, the "msg..." part is right, or I could use __VAR_ARGS__ instead: Variadic Macros - The C Preprocessor ... something I learned today ;-)