7

I always write below code for debug purpose:

printf("%s:%d this is a string %s int %d",__FUNCTION__,__LINE__,strval,intval);

Now since the first part (FUNCTION,LINE) is always used, so I wish to create a macro to do it and just append other debug strings.

Maybe looks like:

#define MYPRINT(args...) printf("%s:%d",__FUNCTION__,__LINE__);printf(##args)

But I wish to use one statement rather than two as above! Is it possible?

Clarify not duplicate of this one

This is different because I wish to add some new field into print command. actually answers here is great, thanks for all's help!

Community
  • 1
  • 1
  • possible duplicate of [How to make a variadic macro (variable number of arguments)](http://stackoverflow.com/questions/679979/how-to-make-a-variadic-macro-variable-number-of-arguments) – Paul Roub Apr 21 '15 at 21:00
  • Are you using GCC exclusively? – jxh Apr 24 '15 at 17:40

3 Answers3

5

If you want a single call to printf(), your MYPRINT needs to be aware of a format string. You can try something like this, so long as the format string is a literal:

#define MYPRINT(FMT, ...) printf("%s:%d " FMT, __FUNCTION__, __LINE__, ##__VA_ARGS__)

The ## is a GCC (and perhaps others) compiler extension that swallows the comma in the case __VA_ARGS__ is actually empty. If your compiler does not support it, leave it off.

jxh
  • 69,070
  • 8
  • 110
  • 193
4

You can use a variadic macro and use , to have one statement:

#define MYPRINT(...) (printf("%s:%d",__FUNCTION__,__LINE__), printf(__VA_ARGS__))
ouah
  • 142,963
  • 15
  • 272
  • 331
  • @Beatlej It's two function calls, but it is still an expression and not a compound statement. Again it has the slight advantage over the selected answer that you can use a string literal like this: `MYPRINT("hello world")` (you don't have to `MYPRINT("%s", "hello world")`. – ouah Apr 22 '15 at 07:44
  • Yes, the standard is missing a way to cleanly treat the variadic macro arguments as if they were variadic arguments to a function. The GCC extension does not care if variadic arguments are missing, but the standard requires at least one argument be present for the `...` in a macro. – jxh Apr 22 '15 at 16:31
1

How about this :

#include <stdio.h>

#define MYPRINT(fmt, ...) \
    printf("[%s]:%d - " fmt "\n", __FUNCTION__, __LINE__, __VA_ARGS__)

int main() {
    char const *s = "My string";
    int i = 42;
    MYPRINT("%s, %d", s, i);
}

Outputs :

[main]:8 - My string, 42
Quentin
  • 62,093
  • 7
  • 131
  • 191
  • This is a nice solution but note that you cannot use a single argument with that macro definition, for example: `MYPRINT("Error!");` is not allowed. – ouah Apr 21 '15 at 21:13