Reputation:
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?
This is different because I wish to add some new field into print command. actually answers here is great, thanks for all's help!
Upvotes: 7
Views: 314
Reputation: 63124
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
Upvotes: 1
Reputation: 70402
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.
Upvotes: 5
Reputation: 145829
You can use a variadic macro and use ,
to have one statement:
#define MYPRINT(...) (printf("%s:%d",__FUNCTION__,__LINE__), printf(__VA_ARGS__))
Upvotes: 4