From b169b5a45d1e7a31359dfb25f75886cad65274fb Mon Sep 17 00:00:00 2001 From: Nirbheek Chauhan Date: Mon, 1 Jul 2019 13:41:58 +0000 Subject: [PATCH] gmacros: Use _Static_assert only for non-expr static assert We can't actually use it inside an expression, so keep the old macro for that. Also add a test so that this doesn't break the next time we change it. See: https://gitlab.gnome.org/GNOME/glib/merge_requests/955#note_542646 --- glib/gmacros.h | 8 +++++++- glib/tests/macros.c | 10 ++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/glib/gmacros.h b/glib/gmacros.h index 1c8d64699..fd81416dd 100644 --- a/glib/gmacros.h +++ b/glib/gmacros.h @@ -734,13 +734,19 @@ #ifndef __GI_SCANNER__ /* The static assert macro really confuses the introspection parser */ #define G_PASTE_ARGS(identifier1,identifier2) identifier1 ## identifier2 #define G_PASTE(identifier1,identifier2) G_PASTE_ARGS (identifier1, identifier2) +#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L +#define G_STATIC_ASSERT(expr) _Static_assert (expr, "Expression evaluates to false") +#elif defined(__cplusplus) && __cplusplus >= 201103L +#define G_STATIC_ASSERT(expr) static_assert (expr, "Expression evaluates to false") +#else #ifdef __COUNTER__ #define G_STATIC_ASSERT(expr) typedef char G_PASTE (_GStaticAssertCompileTimeAssertion_, __COUNTER__)[(expr) ? 1 : -1] G_GNUC_UNUSED #else #define G_STATIC_ASSERT(expr) typedef char G_PASTE (_GStaticAssertCompileTimeAssertion_, __LINE__)[(expr) ? 1 : -1] G_GNUC_UNUSED #endif +#endif /* __STDC_VERSION__ */ #define G_STATIC_ASSERT_EXPR(expr) ((void) sizeof (char[(expr) ? 1 : -1])) -#endif +#endif /* !__GI_SCANNER__ */ /* Provide a string identifying the current code position */ #if defined(__GNUC__) && (__GNUC__ < 3) && !defined(__cplusplus) diff --git a/glib/tests/macros.c b/glib/tests/macros.c index 7fc1d6086..89a1322ee 100644 --- a/glib/tests/macros.c +++ b/glib/tests/macros.c @@ -20,6 +20,15 @@ #include +/* Test that G_STATIC_ASSERT_EXPR can be used as an expression */ +static void +test_assert_static (void) +{ + G_STATIC_ASSERT (4 == 4); + if (G_STATIC_ASSERT_EXPR (1 == 1), sizeof (gchar) == 2) + g_assert_not_reached (); +} + /* Test G_ALIGNOF() gives the same results as the G_STRUCT_OFFSET fallback. This * should be the minimal alignment for the given type. * @@ -48,6 +57,7 @@ main (int argc, g_test_init (&argc, &argv, NULL); g_test_add_func ("/alignof/fallback", test_alignof_fallback); + g_test_add_func ("/assert/static", test_assert_static); return g_test_run (); }