我的代码中有一个警告让我发疯:
int vasprintf_wrapper(char** bufptr, const char* fmt, va_list ap)
{
// Do stuff...
// ...
return vasprintf(bufptr, fmt, ap);
}
Clang (3.6.0),提示“格式字符串不是字符串文字”,指的是正在转发的 fmt
参数。
天真地,我试图:
return vasprintf(bufptr, reinterpret_cast<const char[]>(fmt), ap);
当然不能编译。
我该怎么办?完全禁用警告不是一种选择。我想要警告。但在这种情况下,我想告诉编译器我知道我在做什么(撇开“著名的遗言”笑话......)
最佳答案
使用 __attribute__
标志指示参数是 printf
样式的格式。例如:
__attribute__((__format__ (__printf__, 2, 0)))
int vasprintf_wrapper(char** bufptr, const char* fmt, va_list ap)
{
...
}
最后一个参数 (0
) 禁用对 va_list
的检查。
来自文档:
format (archetype, string-index, first-to-check)
The
format
attribute specifies that a function takesprintf
-,scanf
-,strftime
-, orstrfmon
-style arguments that should be type-checked against a format string.The parameter
archetype
determines how the format string is interpreted.The parameter
string-index
specifies which argument is the format string argument (starting from 1).The parameter
first-to-check
is the number of the first argument to check against the format string. For functions where the arguments are not available to be checked (such asvprintf
), specify the third parameter as zero.
另见:
关于c++ - 更正 "format string is not a string literal"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36120717/