I'm trying to do a debug system but it seems not to work.
What I wanted to accomplish is something like this:
#ifndef DEBUG
#define printd //
#else
#define printd printf
#endif
Is there a way to do that? I have lots of debug messages and I won't like to do:
if (DEBUG)
printf(...)
code
if (DEBUG)
printf(...)
...
The standard way is to use
That way, when you add a semi-colon on the end, it does what you want. As there is no operation the compiler will compile out the "do...while"
You can put all your debug call in a function, let call it
printf_debug
and put theDEBUG
inside this function. The compiler will optimize the empty function.Untested: Edit: Tested, using it by myself by now :)
requires you to not only define
DEBUG
but also give it a non-zer0 value.Appendix: Also works well with
std::cout
As noted by McKay, you will run into problems if you simply try to replace
printd
with//
. Instead, you could use variadric macros to replaceprintd
with a function that does nothing as in the following.Using a debugger like GDB might help too, but sometimes a quick
printf
is enough.No, you can't. Comments are removed from the code before any processing of preprocessing directives begin. For this reason you can't include comment into a macro.
Also, any attempts to "form" a comment later by using any macro trickery are not guaranteed to work. The compiler is not required to recognize "late" comments as comments.
The best way to implement what you want is to use macros with variable arguments in C99 (or, maybe, using the compiler extensions).
On some compilers (including MS VS2010) this will work,
but no grantees for all compilers.