g ++如何获取忽略函数返回值的警告 [英] g++ How to get warning on ignoring function return value

查看:1796
本文介绍了g ++如何获取忽略函数返回值的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

lint产生一些警告,如:

lint produces some warning like:

foo.c XXX Warning 534: Ignoring return value of function bar()

从lint 手动


534忽略函数的返回值

534 Ignoring return value of function

'Symbol'(与位置比较)A
返回一个值的函数是
只是为副作用调用,对于
示例,在一个语句中自己或
逗号
运算符的左侧。 Try:(void)function();到
调用一个函数并忽略它的返回
的值。另请参阅§5.5标记选项中的fvr,fvo和fdr
标记。

'Symbol' (compare with Location) A function that returns a value is called just for side effects as, for example, in a statement by itself or the left-hand side of a comma operator. Try: (void) function(); to call a function and ignore its return value. See also the fvr, fvo and fdr flags in §5.5 "Flag Options".

我想获得此警告,如果存在,在编译期间。在gcc / g ++中有没有任何选项来实现这一点?我已经打开了 -Wall ,但是显然没有检测到这一点。

I want to get this warning, if there exists any, during compilation. Is there any option in gcc/g++ to achieve this? I had turned on -Wall but that apparently did not detect this.

推荐答案

p>感谢 WhirlWind paxdiablo 的答案和评论。

Thanks to WhirlWind and paxdiablo for the answer and comment. Here is my attempt to put the pieces together into a complete (?) answer.

-Wunused-result

-Wno-unused-result

标有属性 warn_unused_result 的函数(请参阅
变量属性)不使用其返回值。默认值为 -Wunused-result

Do not warn if a caller of a function marked with attribute warn_unused_result (see Variable Attributes) does not use its return value. The default is -Wunused-result

函数上的 warn_unused_result 属性。

这是一个完整的例子。文件的内容unused_result.c

Here is a full example. The contents of the file unused_result.c

int foo() { return 3; }

int bar() __attribute__((warn_unused_result));
int bar() { return 5; }

int main()
{
    foo();
    bar();    /* line 9 */
    return 0;
}

和相应的编译结果:

$gcc unused_result.c 
unused_result.c: In function ‘main’:
unused_result.c:9: warning: ignoring return value of ‘bar’, declared with attribute warn_unused_result

再次注意,没有必要使用-Wunused-结果,因为它是默认值。人们可能试图明确地提到它来传达意图。虽然这是一个高尚的意图,但在分析情况后,我的选择,但是,将是反对。因为,在编译选项中有 -Wunused-result 可能会产生一个假的安全/满意感,这是不正确的,除非所有该代码库使用 warn_unused_result 限定。

Note again that it is not necessary to have -Wunused-result since it is default. One may be tempted to explicitly mention it to communicate the intent. Though that is a noble intent, but after analyzing the situation, my choice, however, would be against that. Because, having -Wunused-result in the compile options may generate a false sense of security/satisfaction which is not true unless the all the functions in the code base are qualified with warn_unused_result.

这篇关于g ++如何获取忽略函数返回值的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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