Home > Back-end >  Defining a struct along with a str dictionary using a macro
Defining a struct along with a str dictionary using a macro

Time:02-28

I am trying to automatise the generation of struct in my code for which the syntax is specify by the Midas Library. The difficulty here lies in the parallel building of const char* dictionary that mimic the struct definition:

typedef struct {
  BOOL      runColdStartScript;
  BOOL      runPedestalScript;
  BOOL      triggerCommunicationTest;
  BOOL      updateOdbParameters;
  BOOL      runCmdBuffer;
  BOOL      runSelectedScript;
} myHotLink;
myHotLink hotLinkContainer{};
const char *hot_links_str[9] = { \
  "[.]", \
  "runColdStartScript = BOOL : n", \
  "runPedestalScript = BOOL : n", \
  "triggerCommunicationTest = BOOL : n", \
  "updateOdbParameters = BOOL : n", \
  "runCmdBuffer = BOOL : n", \
  "runSelectedScript = BOOL : n", \
  "", nullptr 
};

Ideally I'd like to generate this piece of code with a macro. For example:

MAKE_HOT_LINK(
  myHotLink,
  { BOOL, runColdStartScript, n },
  { BOOL, runPedestalScript, n },
  ...
)

Does someone have an idea on how to define (and properly call) the MAKE_HOT_LINK macro?

Cheers!

CodePudding user response:

You could use some metamacros to define the fields you want and some other macros that expand those to the declaration and descriptor:

#define MYHOTLINK_FIELDS(M) \
    M(BOOL, runColdStartScript, n) \
    M(BOOL, runPedestalScript, n) \
    M(BOOL, triggerCommunicationTest, n) \
    M(BOOL, updateOdbParameters, n) \
    M(BOOL, runCmdBuffer, n) \
    M(BOOL, runSelectedScript, n) \

#define FIELD_DECL(TYPE, NAME, TAG)  TYPE NAME;
#define FIELD_DESCRIPTOR(TYPE, NAME, TAG)   #NAME " = " #TYPE " : " #TAG,

#define DECLARE_STRUCT(STYPE) struct { STYPE(FIELD_DECL) }
#define STRUCT_DESCRIPTOR(STYPE) { "[.]", STYPE(FIELD_DESCRIPTOR) "", nullptr }

typedef DECLARE_STRUCT(MYHOTLINK_FIELDS) myHotLink;
myHotLink hotLinkContainer {};
const char *hot_links_str[] = STRUCT_DESCRIPTOR(MYHOTLINK_FIELDS);

would expand to (equivalent of) what you have above.

  • Related