]> git.ipfire.org Git - thirdparty/util-linux.git/commitdiff
include: implement ARRAY_SIZE with compiler _Countof if supported
authorCristian Rodríguez <cristian@rodriguez.im>
Mon, 24 Nov 2025 20:04:08 +0000 (17:04 -0300)
committerCristian Rodríguez <cristian@rodriguez.im>
Mon, 24 Nov 2025 20:22:18 +0000 (17:22 -0300)
C2Y has _Countof operator for this.
GCC has an stdcountof.h hedaer and a countof definition
Clang implements _Countof and needs __has_extension check

include/c.h

index f7cd08fd8bb90e8e2f0d783f90cd215dca3be2f8..0126591f2b6e30c29f6ab1aa4e45f69f95c31c47 100644 (file)
@@ -133,6 +133,10 @@ C23   : https://en.cppreference.com/w/c/language/attributes/fallthrough
   #define __has_feature(x) 0
 #endif
 
+#ifndef __has_extension
+  #define __has_extension __has_feature
+#endif
+
 /*
  * Function attributes
  */
@@ -173,6 +177,15 @@ C23   : https://en.cppreference.com/w/c/language/attributes/fallthrough
 #define UL_BUILD_BUG_ON_ZERO(e) __extension__ (sizeof(struct { int:-!!(e); }))
 #define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
 
+#if __has_include(<stdcountof.h>)
+#include <stdcountof.h>
+#define ARRAY_SIZE(arr) countof(arr)
+#endif
+
+#if !defined(ARRAY_SIZE) && __has_extension(c_countof)
+#define ARRAY_SIZE(arr) _Countof(arr)
+#endif
+
 #ifndef ARRAY_SIZE
 # define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]) + __must_be_array(arr))
 #endif