-Werror = format:编译器如何知道 [英] -Werror=format: how can the compiler know
问题描述
我写了这个故意的错误代码
I wrote this intentionally wrong code
printf("%d %d", 1);
使用 g ++
和<$ c $进行编译c> -Werror = format 。
编译器给出了一个非常令人印象深刻的警告:
The compiler gives this very impressive warning:
error: format '%d' expects a matching 'int' argument [-Werror=format]
据我所知,编译器无法告诉代码是错误的,因为直到运行时才解析格式字符串。
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.
我的问题:编译器是否具有可用于printf和类似libc函数的特殊功能,还是我可以将其用于自己的函数?
My question: 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? String literals?
推荐答案
据我所知,编译器无法告诉代码是错误的,因为直到运行时才解析格式字符串。
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
收到有关此警告。
As long as the format string is a string literal, it can be parsed at compile time. If it isn't (which is usually a bad idea anyway), then you can get a warning about that from -Wformat-security
.
编译器是否具有可用于printf和类似libc函数的特殊功能?
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
)。
Yes, as long as you're using the same style of format string as printf
(or various other standard functions like scanf
or strftime
).
void my_printf(Something, char const * format, SomethingElse, ...)
__attribute__ ((format (printf,2,4)));
表示第二个参数是 printf
-style格式字符串,并且要格式化的值从第四个字符开始。参见 http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
to indicate that the second argument is a printf
-style format string, and the values to format begin with the fourth. See http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html.
这篇关于-Werror = format:编译器如何知道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!