Skip to content

Commit 4eb3db1

Browse files
Flavio Ceolinnashif
authored andcommitted
sys: util: Add macro to declare flexible arrays
Flexible arrays are arrays declared without a specific size, e.g: uint8_t my_array[]; They are widely used as as last member in structs that are dynamically allocated. Since C99 they are part of the C standard, but for historical reasons many places still use an older GNU extension that is declare zero length arrays. Although zero length arrays are flexible arrays, we can't blindly replace [0] with [] because of some syntax limitations. This macro workaround these limitations while get rid of this non standard extension. Using true flexible arrays allows the compiler to calculate the size of the array better and improve potential issue checking. Signed-off-by: Flavio Ceolin <[email protected]>
1 parent 4c541eb commit 4eb3db1

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

include/zephyr/sys/util.h

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,29 @@ extern "C" {
129129

130130
#endif /* __cplusplus */
131131

132+
/**
133+
* @brief Declare a flexible array member.
134+
*
135+
* This macro declares a flexible array member in a struct. The member
136+
* is named @p name and has type @p type.
137+
*
138+
* Since C99, flexible arrays are part of the C standard, but for historical
139+
* reasons many places still use an older GNU extension that is declare
140+
* zero length arrays.
141+
*
142+
* Although zero length arrays are flexible arrays, we can't blindly
143+
* replace [0] with [] because of some syntax limitations. This macro
144+
* workaround these limitations.
145+
*
146+
* It is specially useful for cases where flexible arrays are
147+
* used in unions or are not the last element in the struct.
148+
*/
149+
#define FLEXIBLE_ARRAY_DECLARE(type, name) \
150+
struct { \
151+
struct { } __unused_##name; \
152+
type name[]; \
153+
}
154+
132155
/**
133156
* @brief Whether @p ptr is an element of @p array
134157
*

0 commit comments

Comments
 (0)