Re: Debug statements




Keith Thompson wrote:

"Robbie Hatley" <see.my.signature@xxxxxxxxxxxxxxxxxxxx> writes:
[...]
What I do is use a function-like macro called "BLAT", defined
like so:

// In an included header file:
#ifdef BLAT_ENABLE
#define BLAT(X) printf ( X ) ;
#else
#define BLAT(X)
#endif

// In some source file:
#define BLAT_ENABLE
... some code...
BLAT("Length = %f and Height = %f\n", L, H)
...
...
That gives me complaints about passing too many arguments to BLAT.

OOOPS!!! Sorry, I actually use this technique mostly in C++ rather
than C, so in a header I have:

#ifdef BLAT_ENABLE
#define BLAT(X) std::clog << X << std::endl;
#else
#define BLAT(X)
#endif


And in a source file I can do:

BLAT("Text2 = " << Text2)

No commas involved there. That's what's messing up the C
version I presented: the printf function takes multiple
arguments separated by commas, which the preprocessor
interprets as macro argument delimiters.

No reason the same technique won't work in C, but it needs
a bit of tweaking.

I think you need to shift the parentheses from the macro
definition to the invocation, so it looks to the
preprocessor like you're always invoking BLAT with a single
argument:

#ifdef BLAT_ENABLE
#define BLAT(X) printf X
#else
#define BLAT(X)
#endif

...

BLAT(("Length = %f and Height = %f\n", L, H));

Note that I've deleted the semicolon from the macro definition.

That works. Thanks for the tweak! But I'd leave the semicolon
in the macro definition, not the invocation. The reason is,
that way if you "#undef BLAT_ENABLE", even the semicolon
dissappears, and the compiler just sees an empty line.


/* blat-test.c */

#include <stdio.h>

#define BLAT_ENABLE

#ifdef BLAT_ENABLE
#define BLAT(X) printf X;
#else
#define BLAT(X)
#endif

int main (void)
{
int a = 37; int b = 92; int c = a * b;

/* Next line prints a, b, and c if BLAT_ENABLE defined,
* else the preprocessor erases the whole line:
*/
BLAT(("a = %d b = %d axb = %d\n", a, b, c))

return 0;
}


--
Cheers,
Robbie Hatley
lonewolf aatt well dott com
www dott well dott com slant user slant lonewolf slant


.



Relevant Pages