1

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;
    va_start(args,fmt);
    gDbgLog(fmt,args);
    va_end(args);
}

while fmt 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?

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

alk
  • 69,737
  • 10
  • 105
  • 255
stdcerr
  • 13,725
  • 25
  • 71
  • 128
  • It looks like for your example usage you could call the macro directly, i.e. `gDbgLog("some text %d",x);`. Why do you think you need a function wrapper? – bgoldst Aug 12 '16 at 23:54

1 Answers1

0

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.

gDbgLog(fmt,args);

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.

alk
  • 69,737
  • 10
  • 105
  • 255