0

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!?

UserJJ
  • 3
  • 3
  • The macro expansion includes `<<<< expands to func which logs to a file >>>>`. Why not modify the "func which logs to a file"? No need to modify the macro at all. – Peter Dec 13 '19 at 12:43
  • Well, modifying the "func which logs to a file" isn't an option for me. – UserJJ Dec 16 '19 at 08:57

2 Answers2

1

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".

hyde
  • 60,639
  • 21
  • 115
  • 176
  • 1
    Since it's actually tagged C++ (despite being pure C so far), you can use `(std::string{"IP %s"}+fmt).c_str`. This will also concatenate ordinary C strings. – MSalters Dec 13 '19 at 12:47
0

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.

Build Succeeded
  • 1,153
  • 1
  • 10
  • 24