std-aux: implement static-asserts via bitfields

The implementation for static asserts with (sizeof(char[(cond) ? 1 : -1]))
silently fails if the condition is not a compile time constant, because
it results in a VLA which is evaluated at runtime. Well, for that reason
we build with "-Wvla" to catch accidentally using a non-const expression
in a static assert. But still, we can do better. Use instead bitfields
to trigger the compiler error. This works only with static expressions
and also without "-Wvla".

https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/merge_requests/1468
This commit is contained in:
Thomas Haller 2022-11-23 11:03:56 +01:00
parent e292c80da4
commit 18e107e098
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728

View file

@ -293,9 +293,8 @@ _nm_assert_fail_internal(const char *assertion,
#define NM_STATIC_ASSERT(cond) static_assert(cond, "")
#define NM_STATIC_ASSERT_EXPR_1(cond) \
(sizeof(struct { char __static_assert_expr_1[(cond) ? 1 : -1]; }) == 1)
#define NM_STATIC_ASSERT_EXPR_VOID(cond) \
((void) (sizeof(struct { char __static_assert_expr_void[(cond) ? 1 : -1]; }) == 1))
(!!sizeof(struct { unsigned __static_assert_expr_1 : ((cond) ? 2 : -1); }))
#define NM_STATIC_ASSERT_EXPR_VOID(cond) ((void) NM_STATIC_ASSERT_EXPR_1(cond))
/*****************************************************************************/