[英]Avoid defined but not used on static const class
This seems like a trivial thing, but I'm not an expert in C++, and I haven't found a good solution to this online as of yet. 这似乎是一件微不足道的事情,但是我不是C ++专家,而且到目前为止,我还没有找到一个很好的解决方案。 I'm suspecting I'm missing some basic coding construct that might solve this issue.
我怀疑我缺少一些可能解决此问题的基本编码结构。 I have the following definition in one of my main header files:
我的一个主头文件中有以下定义:
static const Foo INVALID_FOO = {};
where Foo
is a POD class (it doesn't have constructors, as it's used in a union in a C++03 project). 其中
Foo
是POD类(它没有构造函数,因为它在C ++ 03项目的联合中使用)。 This seems fine, except for sources which include the header but don't use INVALID_FOO
, I'm getting the warning: 看起来不错,除了包括标头但不使用
INVALID_FOO
,我得到警告:
error: 'Foo::INVALID_FOO' defined but not used [-Werror=unused-variable]
I've tried removing the static
but then I get duplicate definitions. 我尝试删除
static
但随后得到重复的定义。 I could make this a forward declaration, and define it in a .c file, but then the compiler would need to access it through a reference and would not be able to make any optimizations. 我可以使它为前向声明,并在.c文件中定义它,但是编译器将需要通过引用访问它,并且将无法进行任何优化。 I'd also like to not disable the
-Wall
compiler flag. 我也想
-Wall
编译器标志。 I'm wondering if there's a good way to do this? 我想知道是否有一个很好的方法来做到这一点?
You can suppress the GCC warning like this: 您可以像这样禁止显示GCC警告:
static const Foo INVALID_FOO __attribute__ ((unused)) = {};
Note that unused
is correct here, all it does is that it suppresses the warning (and it's still fine to reference the identifier). 请注意,这里
unused
是正确的,它所做的只是抑制警告(并且引用标识符仍然可以)。 There is also a used
attribute which suppresses the warning and tells GCC to emit the definition in the object file even if the compiler does not see a reference to it in the source code—in most cases, this results in unnecessary code bloat. 还有一个
used
属性可以抑制警告, 并告诉GCC在目标文件中发出定义,即使编译器在源代码中没有看到对它的引用-在大多数情况下,这也会导致不必要的代码膨胀。
You can suppress the warning portably using static_cast<void>(INVALID_FOO);
您可以使用
static_cast<void>(INVALID_FOO);
移植该警告static_cast<void>(INVALID_FOO);
statement. 声明。
Also note that static const
at global and namespace scope is a bit of tautology - const
makes it static
, so that static
is superfluous. 还要注意,全局和命名空间范围内的
static const
有点重言而语const
使它成为static
,所以static
是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.