Search code examples
cmacros

Passing macro defined value into another macro string


I thought logically this would work, but I think there is something I'm missing here. I have a set commands stored as macros. The main command is a string that takes two parameters, and the parameters it takes are other defines ranging between integers 0-6.

Macro's:

#define SET_COMMAND(mode,parameter)                     "COMMAND=" #mode "," #paramater "\r"
#define MODE_0                                           1
#define MODE_1                                           2
#define MODE_2                                           3
#define MODE_3                                           4
#define MODE_4                                           5
#define MODE_5                                           6
#define PARAMETER_0                                      0
#define PARAMETER_1                                      1

Then forming the command in run run time:

const char *command = AT_SET_BT_SECURITY(MODE_0, PARAMETER_0);

Then monitoring my serial port the following is printed:

COMMAND=MODE_0,PARAMETER_0

When I would have expected:

COMMAND=1,0

I've tried removing the # from mode and parameter however this still produces the same result.


Solution

  • The solution is to nest the macro:

    #define SET_COMMAND(mode,parameter) SET_COMMAND_(mode, parameter)
    #define SET_COMMAND_(mode,parameter) "COMMAND=" #mode "," #parameter "\r"
    

    Or, a popular option is a separate macro that does the stringification:

    #define STR(...) STR_(__VA_ARGS__)
    #define STR_(...) #__VA_ARGS__
    #define SET_COMMAND(mode,parameter) "COMMAND=" STR(mode) "," STR(parameter) "\r"