How to write generic #define macro in C and write less code

烈酒焚心 提交于 2021-01-02 08:20:52

问题


Let's say I have 2 sets of values for P_A, P_B, P_C as below

#define X_P_A  2
#define X_P_B  3
#define X_P_C  4

#define Y_P_A  5
#define Y_P_B  6
#define Y_P_C  7

There are 3 types of users:- once that only need X variants, once that only need Y variants and once those may need both.

eg

#ifdef X
    #define P_A  X_P_A
    #define P_B  X_P_B
    #define P_C  X_P_C
#endif

#ifdef Y
    #define P_A  Y_P_A
    #define P_B  Y_P_B
    #define P_C  Y_P_C
#endif

Users that need both will make the decision at run time and call X_P_<> or Y_P_<> as needed.

Is there a way to make it simpler, so that I don't have to write conditional macros for each field

ifdef X
// do something magical does defines all P_<> to X_P_<>
#endif

I know it sounds stupid. You may ask why not just use X_P_<> variants on X. I am just trying to understand if it is possible.

I am okay with changing the way the macros the defined. Is something similar to below code possible : (problem with below code is that compilation fails because #if not allowed within #define)

#define A 1
#define B 2
#define C 3

/* Not a correct #define macro */    
#define X_P(x)    \
#if(x == A)    2  \  
#elif(x == B) 3  \ 
#elif(x == C)  4  \
#endif

#ifdef X
 #define P(x) X_P(x)
#endif

回答1:


You could do it with one variant of X-Macros:

#define IMPLEMENT(X) \
    X(P_A, 1, 5) \
    X(P_B, 2, 6) \
    X(P_C, 3, 7)

enum {
    // Just one
    #define X1_P(n, x, y) n = x,
    IMPLEMENT(X1_P)

    // Both
    #define X2_P(n, x, y) X_##n = x,
    #define Y2_P(n, x, y) Y_##n = y,
    IMPLEMENT(X2_P)
    IMPLEMENT(Y2_P)

    DUMMY // Just in case compiler is strict about trailing comma
};

Which would expand to:

enum {
    P_A = 1, P_B = 2, P_C = 3,

    X_P_A = 1, X_P_B = 2, X_P_C = 3,
    Y_P_A = 5, Y_P_B = 6, Y_P_C = 7,

    DUMMY
};



回答2:


#define X_P(x)  ((x) - 0x10 + 1) // 1 is 0x31 and A is 0x41 hence A will give 0x41 - 0x10 + 1 = 0x32
#define Y_P(y)  ((y) - 0x10 + 5) // same logic applies

Would it be what you are looking for ? Not fully answering your question though



来源:https://stackoverflow.com/questions/50292086/how-to-write-generic-define-macro-in-c-and-write-less-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!