[kerneltech] Fwd: [hellogcc] [投稿]小例子,函数声明的重要性

  • From: Li Haifeng <omycle@xxxxxxxxx>
  • To: kerneltech@xxxxxxxxxxxxx
  • Date: Thu, 13 Oct 2011 09:42:44 +0800

---------- 已转发邮件 ----------
发件人: Mingjie Xing <mingjie.xing@xxxxxxxxx>
日期: 2011年9月27日 下午4:31
主题: [hellogcc] [投稿]小例子,函数声明的重要性
收件人: hellogcc@xxxxxxxxxxxxx


xmj@xxxxxxxxxxxx

将函数声明放在头文件里,然后在C文件中包含进来,是一个好的习惯。不然,则可有能导致系统中非常隐蔽的错误。

例子:

$ cat prototype.c
int
main (void)
{
 fun (1);
 return 0;
}

void
fun (void)
{
}

$ gcc prototype.c
prototype.c:9: warning: conflicting types for ‘fun’
prototype.c:4: note: previous implicit declaration of ‘fun’ was here

这里,gcc只给出了警告信息!然而不匹配的传参操作很可能会造成部分代码(还是数据?)被覆写,程序便会出现非常诡异的现象。

$ gcc prototype.c -Werror=implicit-function-declaration
prototype.c: In function ‘main’:
prototype.c:4: error: implicit declaration of function ‘fun’
prototype.c: At top level:
prototype.c:9: warning: conflicting types for ‘fun’
prototype.c:4: note: previous implicit declaration of ‘fun’ was here

可以强制将警告信息升级为错误信息来避免这类问题。

邢明杰



-- 
Li Haifeng
Laboratory of Service Computing Technology and System
Home page:http://tek-life.org

Other related posts:

  • » [kerneltech] Fwd: [hellogcc] [投稿]小例子,函数声明的重要性 - Li Haifeng