自动递增宏扩展

时间:2012-04-02 15:42:13

标签: c macros c-preprocessor

使用普通的 C 预处理器宏,是否可以创建如下内容:

INIT_BASE(0x100)                     // init starting number

#define BASE_A  GET_NEXT_BASE         // equivalent to #define BASE_A 0x101
#define BASE_B  GET_NEXT_BASE         // 0x102
#define BASE_C  GET_NEXT_BASE         // 0x103

2 个答案:

答案 0 :(得分:3)

你试过了吗?

#define BASE_A  (INIT_BASE+1) // equivalent to #define BASE_A 0x101
#define BASE_B  (BASE_A+1)         // 0x102
#define BASE_C  (BASE_B+1)         // 0x103

答案 1 :(得分:3)

宏不能自动进行这种类型的计数,但enum可以。

#define INIT_BASE 0x100
enum foo
{
    BASE_A = INIT_BASE + 1,
    BASE_B,
    BASE_C,
    ...
};

除非确实想要使用宏,否则您将不得不手动进行计数:

#define INIT_BASE  0x100
#define BASE_A    (INIT_BASE + 1)    // equivalent to #define BASE_A 0x101
#define BASE_B    (INIT_BASE + 2)    // 0x102
#define BASE_C    (INIT_BASE + 3)    // 0x103
相关问题