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

2022-01-23 00:00:00 gcc return-value g++ c++ compiler-warnings

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

'符号'(与位置比较)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.

这是一个完整的例子.文件未使用的结果.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 可能会产生一种错误的安全感/满足感,除非代码库中的 all 函数符合以下条件,否则这是不正确的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.

相关文章