hcq0411 发表于 2011-11-03 17:26

gcc有办法对不处理函数返回值的情况发出警告吗?

因为c不像c++可抛异常,不处理就会abort(),很多同事都忘记判断函数返回值,导致一系列问题,调试时头都大了。。。

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

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

EricFisher 发表于 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.
            int fn () __attribute__ ((warn_unused_result));
            int foo ()
            {
                if (fn () < 0) return -1;
                fn ();
                return 0;
            }
results in warning on line 5.

tempname2 发表于 2011-11-15 11:36

不知道有没有通用选项,可以用lint,到时候你就得(void)printf (...)了:luya:

帅绝人寰 发表于 2012-01-13 13:07


int fn () __attribute__ ((warn_unused_result));

或者:

-Wunused-result
页: [1]
查看完整版本: gcc有办法对不处理函数返回值的情况发出警告吗?