使用g++-5.1.1编译器时,只有在使用优化标志时才会警告未使用的变量。

9
在一个大型项目中,我一直收到来自g++-5.1.1的编译器警告,仅在构建发布版本(使用优化标志)时出现,而不是在构建调试版本(禁用大多数编译器优化)时出现。我已经将问题缩小到下面列出的最小示例,并提供了复制问题的命令。如果我使用g++-4.8.4,则不会出现该问题。这是g++-5.1.1的一个错误吗?还是,这段代码做了一些合法上的错误并且需要警告?为什么它不会对代码中列出的最后三种情况产生任何警告(请参见底部的编辑以获取一些解释)?
对于那些感兴趣的人,这里是GCC Bugzilla中的错误报告
/*

This code complains that the variable 'container' is unused only if optimization
flag is used with g++-5.1.1 while g++-4.8.4 does not produce any warnings in
either case.  Here are the commands to try it out:

$ g++ --version
g++ (GCC) 5.1.1 20150618 (Red Hat 5.1.1-4)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ g++ -c -std=c++11 -Wall  -g -O0 test_warnings.cpp

$ g++ -c -std=c++11 -Wall  -O3 test_warnings.cpp
test_warnings.cpp:34:27: warning: ‘container’ defined but not used [-Wunused-variable]
 const std::array<Item, 5> container {} ;
                            ^
*/
#include <array>
struct Item 
{
    int itemValue_ {0} ;
    Item() {} ;
} ;

//
// The warning will go away if you do any one of the following:
// 
// - Comment out the constructor for Item.
// - Remove 'const' from the next line (i.e. make container non-const).
// - Remove '{}' from the next line (i.e. remove initializer list).
//
const std::array<Item, 5> container {} ;
//
// These lines do not produce any warnings:
//
const std::array<Item, 5> container_1 ;
std::array<Item, 5> container_2 ;
std::array<Item, 5> container_3 {} ;

编辑:正如Ryan Haining在评论中提到的那样,container_2container_3将具有extern链接,并且编译器无法警告它们的使用。


2
container_2container_3将具有隐式的extern链接,因此无法知道它们是否被使用。 - Ryan Haining
@RyanHaining,关于那两个你说得很好。我会留下它们来完成所有四种组合(带/不带const{})。 - crayzeewulf
1个回答

1

如果我们查看-Wunused-variable的文档,可以看到这似乎是一个错误(强调我的):

对于C语言,此选项意味着-Wunused-const-variable,但不适用于C++

如果我们查看-Wunused-const-variable,可以看到:

除了声明之外,如果未使用常量静态变量,则发出警告。对于C语言,此警告由-Wunused-variable启用,但对于C++不适用,因为在C++中,const变量代替了C++中的#define。

我们可以看到,在gcc的最新版本中,此警告已经消失了。

这个gcc bug报告:-Wunused-variable ignores unused const initialised variables也很相关。虽然它是针对C的,但C++的情况也被讨论了。


感谢您提供的所有有用信息。看起来警告随着不同版本的gcc使用而翻转,所以它肯定是一个bug。 - crayzeewulf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接