Home > Software engineering >  Macro for creating an enum and array entry at once
Macro for creating an enum and array entry at once

Time:11-10

I have an array of strings (char*). For example:

char* strings[] = 
{
   "abc",
   "def",
   "ghi"
};

To best refer to them by their index, I need to create a separate enum:

typedef enum
{
     abc = 0,
     def,
     ghi

} enum_strings_t;

Assuming I often need to add new entries, I need to do it in 2 places- the strings array and enum_strings_t enum- need to manually keep them in sync.

My question is: can this be somehow fixed by a macro, meaning, that only 1 new entry (instead of 2) would update both the enum and the array? I am looking for a native way of doing this in C, without using external Python scripts that would manually edit the header file.

CodePudding user response:

You could use something what is called Xmacro.

#define XMACRO(X) \
   X(abc) \
   X(def) \
   X(ghi)

#define TO_ENUM(NAME) NAME,
#define TO_STR(NAME)  #NAME,

enum enum_str {
XMACRO(TO_ENUM)
};

char *string[] = {
XMACRO(TO_STR)
};

It expands to:

enum enum_str {
abc, def, ghi,
};

char *string[] = {
"abc", "def", "ghi",
};
  • Related