Having problems with ellipsis in variadic macro

  • I'm trying to make a ripoff of the qDebug function to print a custom-made message output. The idea looks like this:
    @#define DBG(caller, msg_str, ... ) qDebug("equalizer::%s: %s", caller, msg_str, varList )

    #define MSG_ADD_SUCCESS "[0] new value: %d"
    #define MSG_ADD_NULLPTR "[1] error: nullptr"

    #define MSG_REM_SUCCESS "[0] value successfully removed at %d"
    #define MSG_REM_EMPTY "[2] error: Unable to remove value at %d: empty list"
    #define MSG_REM_OOR "[3] error: out of range [%d : %d]"@

    When I compile the code using the definition above I get a lot of: "warning: too many arguments for format [-Wformat-extra-args]" and "expected primary-expression before ')' token" errors,
    There's something terribly wrong in my idea, which is what I came here for. I'm looking for a solution that would allow me to use variadic macros with the same macro structure that I wrote above because I may often need to pass some more parameters, if needed, to qDebug. For example I might want to call it like this:
    @DBG("myfunction", MSG_REM_OOR, 0, 100);@
    which should output:
    @"equalizer::myfunction: [3] error: out of range [0 : 100]"@
    I don't want to write a variadic function to ripoff the qDebug one because that would be totally useless. I could just use qDebug alone, but I would have to write many times the same string format and I want to avoid that.

    Any suggestions?

    p.s. I'm using gcc 4.8.2 compiler (from mingw32/64) on Windows 7, Qt 5.2.0.

  • Useless message removed, please see the edit below

    Forget it all! I got it working, and with no 'ugly' solution, which is:
    @#define DBG(caller, msg_str, args...) qDebug("equalizer::%s: " msg_str, caller, ##args)@
    I concatenated a default string format with msg_str using a simple space and then passed all the arguments. Yep... as simple solution as that... dumb-proof, yet, I missed it at first.
    What I wanted was to concatenate a default message format string with another string msg_str; instead, I was passing msg_str as an argument. So even if msg_str specified more arguments they were interpreted as string literals, not as function arguments, because msg_str was an argument itself - that's why I was getting the “warning: too many arguments for format [-Wformat-extra-args]” warning.

    to prady_80: the ## was a nice suggestion, thanks! I need it for calls wich take no arguments, like MSG_ADD_NULLPTR. This is the solution to the “expected primary-expression before ‘)’ token” error.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.