Reputation: 3
Suppose I have below macro for logging
TRACE(type, sub-type, message, fmt, args);
Now I have a requirement to punch extra argument, say machine IP to this log:
#include <conio.h>
char *IP = "100.200.200.100";
#define TRACE(type, sub-type, message, fmt, args) do{ <<<< expands to func which logs to a file >>>> }while(0)
#define NEW_TRACE(type, sub-type, message, fmt, args) do { \
TRACE (type, sub-type, message, fmt, ##args); \
} while (0)
int main()
{
char *w = "world!";
NEW_TRACE("my-type", "my-subtype", 2, "Hello %s", w);
return 0;
}
How do I write NEW_TRACE such that I punch the 'IP' into the log? Any thoughts!?
Upvotes: 0
Views: 590
Reputation: 62787
If fmt is always string literal, this should work:
#define NEW_TRACE(type, sub-type, message, fmt, args) do { \
TRACE (type, sub-type, message, "IP:%s " fmt, IP, ##args); \
} while (0)
(Disclaimer: untested)
In C++, like C, you can just concatenate string literals, "part1" "part2"
is same as "part1part2"
.
Upvotes: 1
Reputation: 1150
You can extend the macro with variable arguments to macro.
Existing => TRACE( x, y)
Extend => TRACE( x, y, ...)
e.g. #define TRACE(fmt, ...) printf(fmt, ##__VA_ARGS__)
Here VA_AGRS, as well as tricks, can help.
Upvotes: 0