I have an error reporting functionality in my little C library I’m writing. I want to provide an errorf function in addition to the plain error function to allow embedding information in error messages easily.
/*
* Prints a formatted error message. Use it as you would use 'printf'. See the
* 'sio_error' function.
*/
void sio_errorf(const char *format, ...) {
// Print the error prefix
if (g_input == STDIN) fputs("error: ", stderr);
else fprintf(stderr, "%s: ", g_progname);
// Pass on the varargs on to 'vfprintf'.
va_list arglist;
va_start(arglist, format);
// This may produce the following warning -- ignore it:
// warning: format string is not a string literal
vfprintf(stderr, format, arglist);
va_end(arglist);
fputc('\n', stderr);
}
The problem is, I get this warning (compiling with clang 4.0 with the -Weverything switch):
warning: format string is not a string literal
I understand why doing this would be bad. Is there any way I can get rid of this warning? Can I somehow enforce that the format argument sio_errorf be a string literal, so that the compiler knows that it always will be, and that I’m simply passing it on?
I know I can use -Wno-format-nonliteral, but only if other people are going to manually compile it too, they won’t do that. I’d rather something in the source code that silences the warning.
Ideally I would still get the warning if the string I passed to sio_errorf actually isn’t a literal, but I’m not sure if that’s possible.
If you’re using GCC or one of its relatives, try an attribute on the declaration:
To add the attribute to a definition, you can use this: