cerr cerr - 7 months ago 34
C Question

Wrap macro with variable number of arguments

I need to wrap a macro so that it can be accessed with a function.
The macro is defined like:

#define gDbgLog(fmt,...) dbgLog(g_pdbg,MODULE_NAME,__FUNCTION__,fmt,##__VA_ARGS__)

and I've attempted to wrap it up like:

void pMonDbgLog(char* fmt, ...)
va_list args;

seems to come through fine, the arguments (int) seem to get clobbered up. I call it like:

int x = 51144;
pMonDbgLog("some text %d",x);

and what I get is "some text 642129608" while calling the macro directly like
DbgLog("some text %d",x);
works fine. Why is this?

to generate the output.

alk alk

wrap macro with variable number of arguments

It simply is not possible to "expand" a valist to a variable number of arguments and pass those to a variadic functions on run-time, at least not with any additional helpers (which are not part of C and are not portable and might not be available for you implementation/platform).

gDbgLog() expects getting each argument passed separately:

gDbgLog("%s %d", "hello, world", 42);

What the code you show does instead is passing exactly one parameter as the __VA_ARGS__ part, namely the value of valist.


How to solve this?

dbgLog() wraps vsnprintf() to generate the output.

So just drop gDbgLog() and call vsnprintf() from pMonDbgLog() directly passing the valist as initialised by the code snippet you show.