Search code examples
c++variadic-macros

How to add an extra argument to a C++ log macro


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


Solution

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