printf如何发出编译器警告? [英] How can printf issue a compiler warning?

查看:115
本文介绍了printf如何发出编译器警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道函数如何发出编译时警告?

I was wondering how can a function issue a compile-time warning?

这是我的主意,因为当我们在printf(scanf)的第一个参数中为与该类型说明符匹配的变量提供了错误的格式说明符,并使用-Wall选项启用gcc进行编译时,编译器会发出警告.

This came to my mind because when we supply wrong format specifier in the first argument of printf (scanf) for the variable matched with that type specifier and compile with gcc with -Wall option on, compiler issues a warning.

现在,据我了解,printf和scanf是常规实现的可变参数函数,我不知道有什么方法可以在编译时检查字符串的值,更不用说在某些不匹配项时发出警告了.

Now, printf and scanf are regularly implemented variadic functions as I understand and I dont know any way to check the value of the string at the compile-time, let alone issue a warning if something doesnt match.

有人可以解释一下我怎么得到编译器警告吗?

Can someone explain me how I get compiler warning then?

推荐答案

警告是实现(即编译器和 C标准库).您可以让编译器给出很少的警告(查看 tinycc ...),甚至没有...

Warnings are implementation (i.e. compiler & C standard library) specific. You could have a compiler giving very few warnings (look into tinycc...), or even none...

我正在关注最近的 GCC (例如 5.2 ...)在Linux上.

I'm focusing on a recent GCC (e.g. 4.9 or 5.2...) on Linux.

您会收到这样的警告,因为printf是用相应的__attribute__声明的(请参阅GCC 函数属性)

You are getting such warnings, because printf is declared with the appropriate __attribute__ (see GCC function attributes)

(通过 GCC ,您也可以使用format属性...)

(With GCC you can likewise declare your own printf-like functions with the format attribute...)

BTW,一个符合标准的编译器,可以自由地非常专门地实现<stdio.h>头.因此,它可以通过更改其内部状态而无需读取任何头文件 来处理#include <stdio.h>.

BTW, a standard conforming compiler is free to implement very specially the <stdio.h> header. So it could process #include <stdio.h> without reading any header file but by changing its internal state.

您甚至可以添加自己的函数属性,例如通过 MELT

And you could even add your own function attributes, e.g. by customizing your GCC with MELT

这篇关于printf如何发出编译器警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆