如何获取printf风格的编译时警告或错误 [英] How to get printf style compile-time warnings or errors
问题描述
我想像printf一样编写一个例程,而不是功能上的,但我想让例程具有与printf相同的编译检查特性。
I would like to write a routine like printf, not functionally-wise, but rather I'd like the routine to have the same time compile check characteristics as printf.
例如,如果我有:
{
int i;
std::string s;
printf("%d %d",i);
printf("%d",s.c_str());
}
编译器会这样抱怨:
1 cc1plus: warnings being treated as errors
2 In function 'int main()':
3 Line 8: warning: too few arguments for format
4 Line 9: warning: format '%d' expects type 'int', but argument 2 has type 'const char*'
printf和co的特殊函数,编译器对待不同,或有一些技巧,使这个工作在任何用户定义的函数?我感兴趣的特定编译器是gcc和msvc
Are printf and co special functions that the compiler treats differently or is there some trick to getting this to work on any user defined function? The specific compilers I'm interested in are gcc and msvc
推荐答案
不同的编译器可能实现此功能不同。在GCC中,它通过 __ attribute __
指定符和格式
属性来实现(读取它此处)。编译器执行检查的原因只是在GCC提供的标准头文件中 printf
函数声明为 __ attribute __((format(printf ,1,2)))
Different compilers might implement this functionality differently. In GCC it is implemented through __attribute__
specifier with format
attribute (read about it here). The reason why the compiler performs the checking is just that in the standard header files supplied with GCC the printf
function is declared with __attribute__((format(printf, 1, 2)))
完全一样的方式,您可以使用格式
属性扩展相同的格式检查功能到您自己的变量函数,使用与 printf
相同的格式说明符。
In exactly the same way you can use format
attribute to extend the same format-checking functionality to your own variadic functions that use the same format specifiers as printf
.
这一切都只有当你使用的参数传递约定和格式说明符与标准 printf
和 scanf
函数。这些检查被硬编码到编译器中。如果您对变量参数传递使用不同的约定,编译器不会帮助您检查它。
This all will only work if the parameter passing convention and the format specifiers you use are the same as the ones used by the standard printf
and scanf
functions. The checks are hardcoded into the compiler. If you are using a different convention for variadic argument passing, the compiler will not help you to check it.
这篇关于如何获取printf风格的编译时警告或错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!