0

I'm trying to allow printf() like calling in a log function in my C++ app. I found this reference which pretty much explains what I want to do. However, I had no luck getting the concept to work as desired in my app. I scaled it back until I could get the bare minimum program to demonstrate the problem and here it is:

#include <stdarg.h>
#include <stdio.h>
#define logEvent(severity, TAG, fmt, ...) _log_proxy(severity, TAG, fmt"\n", ##__VA_ARGS__)
#define log_level_t int


void _log_proxy(log_level_t severity, const char * TAG, const char *fmt, ...)
        __attribute__((format (printf, 3, 4)));

int main (int argc, const char * argv[]) {
    logEvent(1, "TAG", "This is plain text.");
    logEvent(1, "TAG", "This is a number: %d.", 12);
    logEvent(1, "TAG", "This is a string: %s.", "heebiejeebie");
    return 0;
}

void _log_proxy(log_level_t severity, const char * TAG, const char *fmt, ...) {
    va_list arg;
    va_start(arg, fmt);
    printf(fmt, arg);
    va_end(arg);
}

I find that the arguments to the format string are printed as gibberish in the printf() call. I'm quite certain that I'm doing something very simple wrong, I just don't know what that very simple thing is. Any help would be appreciated.

Community
  • 1
  • 1
The Demigeek
  • 763
  • 3
  • 13
  • 27
  • `_log_proxy` is a [reserved identifier](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier). – chris Oct 25 '14 at 16:05

2 Answers2

4

Replace printf() with the vprintf() that takes the va_list parameter.

printf( char* string , ... )

vprintf( char* string , va_list list )
2501
  • 25,460
  • 4
  • 47
  • 87
2

You want to call vprintf not printf.

printf interprets the va_list as a single argument, printing gibberish (or some other undefined behaviour).

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644