How to clear unused variable warnings created by static assert?

Martin Sebor msebor@gmail.com
Thu Jul 23 15:07:00 GMT 2015


On 07/23/2015 06:50 AM, Jeffrey Walton wrote:
> Our project has a static assert.  Its creating a noisy output at -Wall
> and above. We attempted to manage it with a GCC diagnostic block, but
> its not quite meeting expectations. The static assert creates a bunch
> of unused variable warnings.
>
> We have a UNUSED macro that casts to a void (its the only portable way
> I know to clear an unused warning), but we don't have a variable name
> to use with it.
>
> How can we clear a warning like `unused variable 'assert_26'
> [-Wunused-variable]|`?

One common way is by defining a type. In your case, it can be done
by changing CompileAssert to define a typedef like so:

   template <bool b>
   struct CompileAssert
   {
     typedef char dummy[2*b-1];
   };

and COMPILE_ASSERT_INSTANCE to use the type:

   #define COMPILE_ASSERT_INSTANCE(assertion, instance) \
     typedef CompileAssert<(assertion)>::dummy \
       ASSERT_JOIN(assert_, instance)

This will, however, emit a -Wunused-local-typedefs warning when
used in a local scope.

Using an enum instead can get around that:

   template <bool> struct CompileAssert;
   template <>     struct CompileAssert<true> { };

   #define COMPILE_ASSERT_INSTANCE(assertion, instance) \
     enum { ASSERT_JOIN(assert_, instance) = \
              sizeof (CompileAssert<(assertion)>) }

But perhaps the simplest and least intrusive approach, if you
can't use static_assert, is to annotate the unused variable with
attribute unused:

   #define COMPILE_ASSERT_INSTANCE(assertion, instance) \
     static CompileAssert<(assertion)> \
       ASSERT_JOIN(assert_, instance) __attribute__ ((unused))

Martin



More information about the Gcc-help mailing list