[PATCH v17 01/14] helpers: Add BUILD_BUG_ON from Linux kernel

Daniel Stone daniels at collabora.com
Mon Jul 9 13:23:07 UTC 2018


Import the trivial definition of BUILD_BUG_ON() from the Linux kernel.
This evaluates an expression such that it will call sizeof() on a
negative-length array if the expression is false, generating a compiler
error.

This will be used in future patches to ensure two array lengths don't go
out of sync.

Signed-off-by: Daniel Stone <daniels at collabora.com>
---
 shared/helpers.h | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/shared/helpers.h b/shared/helpers.h
index 46f745d1b..9ecc3c4e9 100644
--- a/shared/helpers.h
+++ b/shared/helpers.h
@@ -100,6 +100,31 @@ extern "C" {
 	(type *)( (char *)__mptr - offsetof(type,member) );})
 #endif
 
+/**
+ * Build-time static assertion support
+ *
+ * A build-time equivalent to assert(), will generate a compilation error
+ * if the supplied condition does not evaluate true.
+ *
+ * The following example demonstrates use of BUILD_BUG_ON to ensure that
+ * arrays which are supposed to mirror each other have a consistent
+ * size.
+ *
+ * @code
+ * int small[4];
+ * long expanded[4];
+ *
+ * BUILD_BUG_ON(ARRAY_LENGTH(small) != ARRAY_LENGTH(expanded));
+ * for (i = 0; i < ARRAY_LENGTH(small); i++)
+ *     expanded[i] = small[4];
+ * @endcode
+ *
+ * @param condition Expression to check for truth
+ */
+#ifndef BUILD_BUG_ON
+#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
+#endif
+
 #ifdef  __cplusplus
 }
 #endif
-- 
2.17.1



More information about the wayland-devel mailing list