2

I have a function with a printf-like variable parameter list that I call for example with:

debugMsg(__FILE__, __LINE__, "failed with var %s = %d\n", var, val);

Now I need a wrapper function for this, e.g.:

void debugMsgWrapper(const char* FileName, int LineNo, const char* FmtStr, ...)
{
    // do some other things
    DebugMsg(FileName, LineNo, FmtStr, ...);
}

Of course this doesn't work with the parameter list specified as ... but I don't have any idea how to copy the parameter list to the called function. I had a look at
void va_copy(va_list dest, va_list src);
but could not find how to use it.

How can I give the variable parameter list to the called function?

Ingo
  • 588
  • 9
  • 21
  • 1
    The key part of the answer from that post: "*You cannot pass the variadic arguments to a variadic function. Instead, you must call a function that takes a va_list as argument.*" – kaylum Oct 11 '21 at 00:54

1 Answers1

2

You need to re-write debugMsg so that it takes a va_list instead of a variable number of arguments. Here's how you'd do it:

void
debugMsg(const char *FileName, int LineNo, const char *FmtStr, va_list args);

void
debugMsgWrapper(const char *FileName, int LineNo, const char *FmtStr, ...)
{
    va_list args;

    // do some other things
    va_start(args, FmtStr); // Make args start after FmtStr;
    debugMsg(FileName, LineNo, FmtStr, args);
    va_end(args);
}

You can then, in debugMsg, repeatedly pull arguments from args via va_arg:

int n;
const char *string;

n = va_arg(args, int);
string = va_args(args, char*);
Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 1
    Thanks for the solution :) Isn't there a typo with `char char *FmtStr`? Shouldn't it be `const char *FmtStr`? – Ingo Oct 11 '21 at 08:54