c++ - GCC -Wuninitialized/-Wmaybe-uninitialized 问题

标签 c++ c gcc compiler-optimization gcc-warning

我在使用 gcc-4.7 (Ubuntu/Linaro 4.7.2-11precise2) 4.7.2 时遇到了一个非常奇怪的问题。我无法在没有警告的情况下编译以下有效代码:

extern void dostuff(void);

int test(int arg1, int arg2)
{
    int ret;

    if (arg1) ret = arg2 ? 1 : 2;

    dostuff();

    if (arg1) return ret;

    return 0;
}

编译选项和输出:

$ gcc-4.7 -o test.o -c -Os test.c -Wall
test.c: In function ‘test’:
test.c:5:6: warning: ‘ret’ may be used uninitialized in this function [-Wmaybe-uninitialized]

但是,以下代码编译时没有警告(尽管汇编效率稍低):

extern void dostuff(void);

int test(int arg1, int arg2)
{
    int ret;

    if (arg1 && arg2) ret = 1;
    if (arg1 && !arg2) ret = 2;

    dostuff();

    if (arg1) return ret;

    return 0;
}

我有点卡住了,正在考虑这是一个编译器错误。有什么想法吗?

最佳答案

这确实是 gcc 中的一个已知问题。
gcc 因报告 incorrect uninitialized variables 而臭名昭著
不足之处已及时指出,并有克服不足的主动权:
Better Uninitialized Warnings :

The GNU Compiler Collection warns about the use of uninitialized variables with the option -Wuninitialized. However, the current implementation has some perceived shortcomings. On one hand, some users would like more verbose and consistent warnings. On the other hand, some users would like to get as few warnings as possible. The goal of this project is to implement both possibilities while at the same time improving the current capabilities.

该计划旨在提供更好的警告,并引用了与您的案例相似的示例案例。相关部分是:

What an user understands as a false positive may be different for the particular user. Some users are interested in cases that are hidden because of actions of the optimizers combined with the current environment. However, many users aren't, since that case is hidden because it cannot arise in the compiled code. The canonical example is

int x;
if (f ())
     x = 3;
return x;

where 'f' always return non-zero for the current environment, and thus, it may be optimized away. Here, a group of users would like to get an uninitialized warning since 'f' may return zero when compiled elsewhere. Yet, other group of users would consider spurious a warning about a situation that cannot arise in the executable being compiled.

关于c++ - GCC -Wuninitialized/-Wmaybe-uninitialized 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14132898/

相关文章:

c++ - GCC 编译错误 : no match for ‘operator<’

c++ - fork 子和父运行单独的代码

c++ - 在抽象类 c 的子类中使用来自抽象类的引用

c++ - 收到 "vector iterators incompatible"错误

c - 如何从内核中获取总物理内存

c++ - gcc: undefined reference 错误

c++ - 进程后的 CloseHandle 不存在

c - 如何从 elf 调用和编译函数到我的二进制文件?

c++ - 使用 Eclipse 编译 xerces-c++ 程序

gcc - 迄今为止最稳定的 gcc/g++ 版本