Skip to content

gmacros: Use _Static_assert when C11 is available

Nirbheek Chauhan requested to merge nirbheek/static-assert-c11 into master

The static assert message is much nicer to read, and is less likely to be misinterpreted as a false positive.

glib is built with -std=gnu89, but this macro will be available to projects that use glib with c11 or gnu11. I built glib with -Dc_std=gnu11 to verify that it works fine with glib's code. I have also built all of gstreamer to confirm that nothing breaks in there.

Before:

In file included from glib/glibconfig.h:9,
                 from ../glib/gtypes.h:32,
                 from ../glib/gatomic.h:27,
                 from ../glib/gatomic.c:22:
../glib/gmacros.h:743:53: error: size of array ‘_GStaticAssertCompileTimeAssertion_1’ is negative
  743 | #define G_STATIC_ASSERT(expr) typedef char G_PASTE (_GStaticAssertCompileTimeAssertion_, __COUNTER__)[(expr) ? 1 : -1] G_GNUC_UNUSED
      |                                                     ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
../glib/gmacros.h:735:47: note: in definition of macro ‘G_PASTE_ARGS’
  735 | #define G_PASTE_ARGS(identifier1,identifier2) identifier1 ## identifier2
      |                                               ^~~~~~~~~~~
../glib/gmacros.h:743:44: note: in expansion of macro ‘G_PASTE’
  743 | #define G_STATIC_ASSERT(expr) typedef char G_PASTE (_GStaticAssertCompileTimeAssertion_, __COUNTER__)[(expr) ? 1 : -1] G_GNUC_UNUSED
      |                                            ^~~~~~~
../glib/gatomic.c:102:1: note: in expansion of macro ‘G_STATIC_ASSERT’
  102 | G_STATIC_ASSERT (sizeof (gint) == 8);
      | ^~~~~~~~~~~~~~~

After:

In file included from glib/glibconfig.h:9,
                 from ../glib/gtypes.h:32,
                 from ../glib/gatomic.h:27,
                 from ../glib/gatomic.c:22:
../glib/gmacros.h:739:31: error: static assertion failed: "Expression evaluates to false"
  739 | #define G_STATIC_ASSERT(expr) _Static_assert (expr, "Expression evaluates to false")
      |                               ^~~~~~~~~~~~~~
../glib/gatomic.c:102:1: note: in expansion of macro ‘G_STATIC_ASSERT’
  102 | G_STATIC_ASSERT (sizeof (gint) == 8);
      | ^~~~~~~~~~~~~~~
Edited by Nirbheek Chauhan

Merge request reports