chiark / gitweb /
utils/macros.h: Introduce a `STATIC_ASSERT' macro.
authorMark Wooding <mdw@distorted.org.uk>
Thu, 26 Sep 2019 19:18:11 +0000 (20:18 +0100)
committerMark Wooding <mdw@distorted.org.uk>
Fri, 27 Sep 2019 00:06:09 +0000 (01:06 +0100)
utils/macros.3
utils/macros.h

index a2a90033b5e87ac95cffeeb8ecdd6bf35a5b11c2..98ab23861629d91f2e4025e194bf29a942d46839 100644 (file)
@@ -5,6 +5,7 @@ macros \- useful macros
 .\" @N
 .\" @STR
 .\" @GLUE
+.\" @STATIC_ASSERT
 .\" @DISCARD
 .\" @IGNORE
 .\" @DEPRECATED
@@ -24,6 +25,7 @@ macros \- useful macros
 .BI "size_t N(" array ");"
 .BI "STR(" tokens\fR... ")"
 .BI "GLUE(" tokens\fR... ", " tokens\fR... ")"
+.BI "STATIC_ASSERT(" cond ", " msg ");"
 
 .BI "void DISCARD(" scalar ");"
 .BI "void IGNORE(" variable ");"
@@ -64,6 +66,18 @@ and the result of gluing these tokens together must be valid
 preprocessing token.
 .PP
 The
+.B STATIC_ASSERT
+causes compilation to fail if the integer constant expression
+.I cond
+evaluates to zero.  This macro uses the C11
+.B static_assert
+declaration if available, and the
+.I msg
+will be reported in the compiler's diagnostic messsage; otherwise, the macro
+falls back to a somewhat ugly hack which currently ignores the
+.IR msg .
+.PP
+The
 .B DISCARD
 macro discards its argument, which must be of some scalar type.  This
 can be useful in muffling warnings about ignoring return codes in cases
index 5f432f7e9b3c25b82884214df5bb3d388702add9..9e27a4813a4b3f8997e2ba85784d587023d87778 100644 (file)
@@ -34,6 +34,8 @@
 
 /*----- Header files ------------------------------------------------------*/
 
+#include <assert.h>
+
 #ifndef MLIB_COMPILER_H
 #  include "compiler.h"
 #endif
 #define MLIB__GLUE(x, y) x##y
 #define GLUE(x, y) MLIB__GLUE(x, y)
 
+#ifdef static_assert
+#  define STATIC_ASSERT(cond, msg) static_assert(cond, msg)
+#else
+#  define STATIC_ASSERT(cond, msg)                                     \
+       IGNORABLE extern char static_assert_failed[2*!!(cond) - 1]
+#endif
+
 /*----- Compiler diagnostics ----------------------------------------------*/
 
 /* --- Compiler-specific definitions --- */