I am trying to automatically declare a given data structure from an enum value. A simple example is worth thousand words:
#define X_FIELDS \
X(A, upd_foo) \
X(B, upd_bar)
enum MSGS_TYPES {
#define X(msg_type, data_type) msg_type,
X_FIELDS
#undef X
MSGS_SIZE
};
#define DECLARE_MSG(name, type) X(type) name = { type };
typedef struct {
enum MSGS_TYPES type;
int x;
} upd_foo;
typedef struct {
enum MSGS_TYPES type;
int y;
} upd_bar;
int main() {
DECLARE_MSG(msg, B);
printf("%d\n", msg.type);
msg.y = 0;
return 0;
}
Here, I'd like for DECLARE_MSG macro to declare
upd_bar msg = { B };
Is there any way to achieve that?
Note that I already tried something like:
#define T_A upd_foo
#define T_B upd_bar
#define _T(type) T_type
#define X(type) _T(type)
#define DECLARE_MSG(name, type) X(type) name = { type };
But it obviously isn't working, complaining that ‘T_type’ is an unknown type name.
Thank you very much!
T_type
is considered single token, and type
argument is not found on macro expansion.
You need to use concatenation operator ##
:
#define _T(type) T_##type