c++ - -错误=格式: how can the compiler know

标签 c++ c compiler-construction libc

我故意写错了代码

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 相同样式的格式字符串(或各种其他标准函数,如 scanfstrftime).

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/

相关文章:

c++ - 字符串到 LPCTSTR

c# - 从 C++ 到 C# 的回调

c++ - 派生的继承存储地址

将库版本编译成.so文件

c - 当互斥体可用时在哪里使用二进制信号量?

java - 我自己的Java编译器和字节码: Problems invoking functions

c++ - 在 Visual C++ 的命令行上编译

ruby - 一种语言如何被自身解释(如 Rubinius)?

c++ - 使用 boost::is_any_of 拆分会混淆定界符 ",,"和 ","

更改命令行参数