Reputation: 773
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.
Upvotes: 0
Views: 120
Reputation: 254701
You want to call vprintf
not printf
.
printf
interprets the va_list
as a single argument, printing gibberish (or some other undefined behaviour).
Upvotes: 2