免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 4764 | 回复: 3
打印 上一主题 下一主题

gcc有办法对不处理函数返回值的情况发出警告吗? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-11-03 17:26 |只看该作者 |倒序浏览
因为c不像c++可抛异常,不处理就会abort(),很多同事都忘记判断函数返回值,导致一系列问题,调试时头都大了。。。

请问各位,gcc是否可以做到?
比如
int sum(int a, int b) { return a+b }
int main()
{
      sum(1, 2);
      return 0;
}
就可以打印出警告来,说sum()函数的返回值没有被使用。(至少用一个变量接住吧。)

我试了-Wreturn-type,没有用。。。

论坛徽章:
2
摩羯座
日期:2013-10-10 14:29:04天蝎座
日期:2014-01-03 09:14:49
2 [报告]
发表于 2011-11-04 17:24 |只看该作者
gcc没有提供这样的一个通用选项,而是提供了一个属性,用来指定单个函数。

warn_unused_result
    The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug, such as realloc.

  1.               int fn () __attribute__ ((warn_unused_result));
  2.               int foo ()
  3.               {
  4.                 if (fn () < 0) return -1;
  5.                 fn ();
  6.                 return 0;
  7.               }
复制代码
results in warning on line 5.

论坛徽章:
2
CU十二周年纪念徽章
日期:2013-10-24 15:41:34处女座
日期:2013-12-27 22:22:41
3 [报告]
发表于 2011-11-15 11:36 |只看该作者
不知道有没有通用选项,可以用lint,到时候你就得(void)printf (...)了

论坛徽章:
2
2015年辞旧岁徽章
日期:2015-03-03 16:54:152015年迎新春徽章
日期:2015-03-04 09:53:17
4 [报告]
发表于 2012-01-13 13:07 |只看该作者

int fn () __attribute__ ((warn_unused_result));

或者:

-Wunused-result
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP