c / expert
Snippet
X-Macros for Synchronized Definitions
The X-Macro pattern is a powerful preprocessor technique used to maintain multiple related lists (like enums, strings, or switch cases) in sync. You define a list once and then 'apply' it by redefining the 'X' macro before each use. This prevents errors where an enum is updated but the corresponding string array is forgotten.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#define STATUS_LIST \X(IDLE, "System is waiting") \X(BUSY, "Processing task") \X(ERROR, "Fault detected")// Generate Enumtypedef enum {#define X(a, b) STATUS_##a,STATUS_LIST#undef X} status_t;// Generate String Tableconst char* status_msg[] = {#define X(a, b) b,STATUS_LIST#undef X};
Breakdown
1
#define STATUS_LIST \
Defines the master list of items and their associated metadata.
2
X(IDLE, "System is waiting")
An entry in the list; X is a placeholder for a future macro.
3
#define X(a, b) STATUS_##a,
Redefines X to extract the first argument and append it to a prefix for the enum.
4
STATUS_LIST
Expands the master list using the current definition of X.