g++ 如何在忽略函数返回值时获得警告

g++ How to get warning on ignoring function return value(g++ 如何在忽略函数返回值时获得警告)

本文介绍了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返回值的函数是只是为了副作用而调用,因为例如,在一个声明本身或逗号的左侧操作员.尝试:(无效)函数();到调用一个函数并忽略它的返回价值.另见 fvr、fvo 和 fdr§5.5标志选项"中的标志.

'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.

推荐答案

感谢 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 相关的 gcc 选项.并且默认开启.引用自 gcc 警告选项页面:

-Wunused-result is the relevant gcc option. And it is turned on by default. Quoting from gcc warning options page:

-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 属性.

So, the solution is to apply the warn_unused_result attribute on the function.

这是一个完整的例子.文件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-result,因为它是默认的.人们可能会想明确提及它来传达意图.虽然那是高尚的意图,但分析情况后,我的选择却是反对的.因为,在编译选项中使用 -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++ 如何在忽略函数返回值时获得警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:g++ 如何在忽略函数返回值时获得警告