使用-Werror时如何忽略错误?

时间:2016-08-09 01:15:35

标签: gcc gcc-warning

我有以下测试代码test.c

#include<stdio.h>
int *func()
{
    int i = 123;
    return &i;
}

int main()
{
    printf("%d\n", *func());
}

如果我使用命令编译就可以了:

gcc test.c -o test

它将有以下警告信息:

warning: address of stack memory associated with local variable 'i'
  returned [-Wreturn-stack-address]
return &i;
        ^
1 warning generated.   

但它可以输出结果:123

如果我使用命令:

gcc -Werror test.c -o test

它将包含以下错误信息:

error: address of stack memory associated with local variable 'i'
  returned [-Werror,-Wreturn-stack-address]
return &i;
        ^
1 error generated. 

现在我想使用-Werror选项,但我也想忽略address of stack memory associated with local variable 'i'警告,我该怎么办?

1 个答案:

答案 0 :(得分:2)

可以通过在gcc前面加上警告名称来禁用大多数no-警告,例如: -Wno-return-stack-address

那就是说,这不是你想忽略的;返回指向堆栈变量的指针是未定义的行为,虽然它在大多数编译器上具有半可预测的结果,但它非常脆弱;任何函数调用,无论是隐式还是显式,都可以扼杀指针引用的值。