如何在C语言中编写通用的#define宏并编写更少的代码 [英] How to write generic #define macro in C and write less code

查看:56
本文介绍了如何在C语言中编写通用的#define宏并编写更少的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下两组P_A,P_B,P_C值

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

共有3种类型的用户:-一次只需要X个变体,一次只需要Y个变体,而一次可能需要两者.

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

例如

#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

同时需要这两者的用户将在运行时做出决定,并根据需要调用X_P_<>或Y_P_<>.

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

我知道这听起来很愚蠢.您可能会问为什么不只在X上使用X_P_<>变体.我只是想了解是否有可能.

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.

我可以更改定义宏的方式.可能与以下代码类似:(以下代码的问题是编译失败,因为#define中不允许#if)

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

推荐答案

您可以使用X-Macros的一种变体来实现:

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
};

将扩展为:

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
};

这篇关于如何在C语言中编写通用的#define宏并编写更少的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆