Search code examples
c++macrosvariadic-functionsvariadicvariadic-macros

Calling a printf with __VA_ARGS__ not working in a function but works in a macro


The following macro works:

#define DEBUG(msg, ...) printf(msg, __VA_ARGS__)

But when I add my own function, it says error: '__VA_ARGS__' was not declared in this scope. My code:

void Debug(const char* msg, ...) {
    printf(msg, __VA_ARGS__);
}

#define DEBUG(msg, ...) Debug(msg, __VA_ARGS__)

Is there any way to do so?


Solution

  • __VA_ARGS__ simply does not exist outside of a variadic macro. For what you are attempting, use vprintf() instead of printf(), eg:

    void Debug(const char* msg, ...) {
        va_list args;
        va_start(args, msg);
        vprintf(msg, args);
        va_end(args);
    }
    
    #define DEBUG(msg, ...) Debug(msg, __VA_ARGS__)