我故意写错了代码
printf("%d %d", 1);
使用 g++
和 -Werror=format
编译。
编译器给出了这个非常令人印象深刻的警告:
error: format '%d' expects a matching 'int' argument [-Werror=format]
据我所知,编译器无法判断代码是错误的,因为格式字符串直到运行时才被解析。
我的问题:编译器是否具有启动 printf 和类似 libc 函数的特殊功能,或者这是我可以用于我自己的函数的功能?字符串文字?
最佳答案
As far as I can see, there's no way the compiler can tell that the code is wrong, because the format string isn't parsed until runtime.
只要格式字符串是字符串字面量,就可以在编译时解析。如果不是(无论如何这通常是个坏主意),那么您可以从 -Wformat-security
获得警告。
does the compiler have a special feature that kicks in for printf and similar libc functions?
是的。
or is this a feature I could use for my own functions?
是的,只要您使用与 printf
相同样式的格式字符串(或各种其他标准函数,如 scanf
或 strftime
).
void my_printf(Something, char const * format, SomethingElse, ...)
__attribute__ ((format (printf,2,4)));
表示第二个参数是 printf
样式的格式字符串,要格式化的值从第四个开始。参见 http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html .
关于c++ - -错误=格式: how can the compiler know,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20424625/