how could I write this cpp macro

B

Bilgehan.Balban

Hi,

I'm trying to convert this:

printf("format str %s, %s", "str arg 1", "str arg 2 etc.");

to this:

printf("%s: " "format str %s, %s", __FUNCTION__, "str arg 1", "str arg2
etc.");

All sol'ns I came up had various problems in various printf formats.
The closest I had was something like:

#if DEBUG > 0
#define pdebug(fmt ...) printf("%s: " fmt, \
__FUNCTION__, __VA_ARGS__); \
#endif

But this wont work if there's a printf with no va_args, such as:

printf("fmt string and nothing else\n");

because the comma after __FUNCTION__ will be a syntax error.

Any ideas?

Thanks,
Bahadir
 
B

Ben Pfaff

I'm trying to convert this:

printf("format str %s, %s", "str arg 1", "str arg 2 etc.");

to this:

printf("%s: " "format str %s, %s", __FUNCTION__, "str arg 1", "str arg2
etc.");

It's ghastly, but
#define pdebug printf("%s:", __FUNCTION__), printf
might do what you want.

There are probably C99-specific solutions, and definitely
GCC-specific solutions, as well.
 
L

L7

Hi,

I'm trying to convert this:

printf("format str %s, %s", "str arg 1", "str arg 2 etc.");

to this:

printf("%s: " "format str %s, %s", __FUNCTION__, "str arg 1", "str arg2
etc.");

All sol'ns I came up had various problems in various printf formats.
The closest I had was something like:

#if DEBUG > 0
#define pdebug(fmt ...) printf("%s: " fmt, \
__FUNCTION__, __VA_ARGS__); \
#endif

But this wont work if there's a printf with no va_args, such as:

printf("fmt string and nothing else\n");

because the comma after __FUNCTION__ will be a syntax error.

Any ideas?

#define pdebug(args...) do { \
printf ("%s:", __FUNCTION__); \
printf (args); \
} while (0);

Should do what you want.
 
D

David Resnick

Ben said:
It's ghastly, but
#define pdebug printf("%s:", __FUNCTION__), printf
might do what you want.

There are probably C99-specific solutions, and definitely
GCC-specific solutions, as well.

I think Ben's solution or a variant of it may be what you want. Your
method of concatenating string literals precludes people from using a
variable as the format string, not ideal if this is to be widely used.
e.g.

const char *format = "%s %d %s";
pdebug(format, foo, bar, bas);

would break.

-David
 
E

Eric Sosman

L7 wrote On 08/31/06 13:58,:
#define pdebug(args...) do { \
printf ("%s:", __FUNCTION__); \
printf (args); \
} while (0);

Should do what you want.

Lose the final semicolon.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,764
Messages
2,569,566
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top