Search code examples
cmacrosc-preprocessorstringification

save expanded macro result before it is undefined


With GCC, I am using X-macros for a collection of variables.

#define TEST_MAP    \
        X(0, 1, 2)  \
        X(0, 2, 2)  \
        X(0, 3, 5)

Let's suppose I need to sum up all the 2nd fields

#define X(a,b,c) (+b)   /* sum all 2nd elements of TEST_MAP */
uint16_t d = (TEST_MAP);
#undef X

That works fine, because TEST_MAP is expanded as

uint16_t d = ((+1) (+2) (+3));

However, I'd prefer to use a compile-time constant, but if I do

#define X(a,b,c) (+b)   /* sum all 2nd elements of TEST_MAP */
#define D (TEST_MAP)
#undef X

uint16_t d = D;

of course it won't work because at the time D is expanded X is not defined anymore, so I have:

uint16_t d = (X(0, 1, 2) X(0, 2, 2) X(0, 3, 5));

I have checked the use of # and ## but I haven't found yet how to solve this. How can I force #define D to expand to ((+1) (+2) (+3)) ?


Solution

  • Use enumeration:

    #define X(a,b,c) (+b)   /* sum all 2nd elements of TEST_MAP */
    enum { D = (TEST_MAP) };
    #undef X