Reputation: 117
I have 3 very similar log functions that will be called from different places.
void INFO (char *format, ...) {
char log_buf[256] = {0};
va_list args;
va_start(args, format);
vsprintf(log_buf, format, args);
va_end(args);
LIB_LOG_INFO(log_buf);
}
void ERROR (char *format, ...) {
char log_buf[256] = {0};
va_list args;
va_start(args, format);
vsprintf(log_buf, format, args);
va_end(args);
LIB_LOG_ERROR(log_buf);
}
void DEBUG (char *format, ...) {
char log_buf[256] = {0};
va_list args;
va_start(args, format);
vsprintf(log_buf, format, args);
va_end(args);
LIB_LOG_DEBUG(log_buf);
}
I cannot pass any extra arguments, so I cannot do an if-else to call the different LIB_LOG functions.
Is it possible to write a generic macro that will expand into these 3 function definitions at compile time? Only the names of the LIB_LOG functions are different.
Upvotes: 0
Views: 1318
Reputation: 213678
First of all please note that variable argument functions in particular are almost certainly the wrong solution to any problem. They are to be regarded as a deprecated, dangerous feature - avoid them if possible.
The being said, you can solve your problem by making a single generic function that takes a function pointer parameter:
typedef void lib_log_func_t (char* buf);
void lib_log (lib_log_func_t* func, const char* format, ...)
{
char log_buf[256] = {0};
va_list args;
vsprintf(log_buf, format, args);
va_end(args);
func(log_buf);
}
Then write 3 wrapper macros:
#define INFO(format, ...) lib_log(LIB_LOG_INFO, format, __VA_ARGS__)
#define ERROR(format, ...) lib_log(LIB_LOG_ERROR, format, __VA_ARGS__)
#define DEBUG(format, ...) lib_log(LIB_LOG_DEBUG, format, __VA_ARGS__)
Upvotes: 2