Visual Studio 2015 introduced two new warnings, C4473 and C4477, which inform when a string formatting function has a mismatch between the format string and the associated variadic arguments:
warning C4473: 'printf' : not enough arguments passed for format string
warning C4477: 'printf' : format string '%p' requires an argument of type 'void *', but variadic argument 1 has type 'int'
Those warnings are very helpful and have been supported for a while by other popular compilers (gcc and clang, with the -wformat
option I believe, although I'm much less familiar with these compilers).
Now my problem is that I want to use a custom Log(format, ...)
function to handle logging, that would do additional work (for example, write to a file and the console, or add a timestamp).
But for the sake of this question, let's just assume I'm simply wrapping a call to printf
:
void Log(const char * format, ...)
{
va_list args;
va_start(args, format);
printf(format, args);
va_end(args);
}
By doing that, I don't have the warnings displayed above if I call my Log
function with mismatching arguments:
printf("Error: %p\n", 'a'); // warning C4477
printf("Error: %p\n"); // warning C4473
Log("Error: %p\n", 'a'); // no warning
Log("Error: %p\n"); // no warning
Is there a way to tell the compiler that it should check the variadic arguments of my function the same way it does with printf
? Especially for MSVC compiler but a solution that works for gcc and clang would be appreciated too.
__declspec
keyword, but it doesn't seem to have specifiers for format strings. You could find the declaration of e.g.printf
in the header files, and see if there's some special declaration keywords or identifiers for it. And if not, then you're out of luck.Log()
also callsnprintf(0,0 ...;
? ( a bit sloppy though for args with side effects.)