John John - 1 year ago 62
C++ Question

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. 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 = {};

is a POD class (it doesn't have constructors, as it's used in a union in a C++03 project). This seems fine, except for sources which include the header but don't use
, I'm getting the warning:

error: 'Foo::INVALID_FOO' defined but not used [-Werror=unused-variable]

I've tried removing the
but then I get duplicate definitions. 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. I'd also like to not disable the
compiler flag. I'm wondering if there's a good way to do this?

Answer Source

You can suppress the GCC warning like this:

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). 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download