In a multi-threaded program I’m writing a custom print function which accepts a variable argument list.
void t_printf(char * str, ...)
{
if(file_ptr != NULL)
{
va_list ap;
va_start(ap, str);
vfprintf(file_ptr, str, ap);
va_end(ap);
fflush(file_ptr);
}
}
Inside this function I want to add the current thread id (using pthread_self()) to the message getting printed. How can I do it? Is there a way to add it to the existing va_list?
With a variadic macro:
With a variadic macro you can call the function with an argument prepended or appended:
This prepends the
thread_idbefore other arguments. (Note that on the_t_printf()function you have to modify the format string too.)If you do this:
This will expand do this:
If
t_printf()is called without other argument that format, you will have a trailing comma. GCC has a##extension that takes care of adding the comma as needed:Complete solution with the macro:
Without modifying the arguments
An other solution is to do two printf()s:
Complete solution: