C #define基于另一个#define错误

时间:2016-04-08 14:04:13

标签: c c-preprocessor

所以我的Visual Studio声明tag1和tag2都是未定义的,但是它们是清晰定义的,我可以根据另一个定义一个吗?

#define push                99
#define last_instruction    push

#ifdef DEBUG
    #define new_instr   (1+last_instruction) //should be 100
    #undef  last_instruction
    #define last_instruction   new_instr    //redifine to 100 if debug
#endif

我有一些tag2的情况,它说定义必须是const,但它是常数,它是1 + 99,任何帮助将不胜感激。

谢谢! BA

3 个答案:

答案 0 :(得分:4)

首先,您无法两次定义相同的宏。如果您需要替换宏,首先必须#undef

#define tag1    99
#ifdef DEBUG
    #define tag2   (1+tag1)
    #undef tag1
    #define tag1   tag2
#endif

但这不会解决问题。宏不是变量,您不能使用它们存储值以便稍后重复使用。它们是文本替换,因此它们并行存在。

因此新定义#define tag1 tag2扩展为1+tag1。但是在这一点上,没有任何名为tag1的东西,因为我们只是未定义它,我们还没有重新定义它。

过多地考虑这一点,你会变得疯狂:)所以只要忘记整件事,你真正想做的就是:

#define tag1_val  99
#define tag1      tag1_val

#ifdef DEBUG
    #undef tag1
    #define tag1  (tag1_val+1)
#endif

答案 1 :(得分:1)

如果你想要的只是一些整数常量的符号名称,你可以像enum一样定义它们:

enum {
    push = 99,
#ifdef DEBUG
    new_instr,
#endif
    last_plus_1,
    last_instr = last_plus_1 - 1
};

new_instr将为100(如果定义DEBUG),last_plus_1将为101(如果DEBUG已定义)或100(如果DEBUG未定义) ,last_instr将比last_plus_1少一个。

答案 2 :(得分:0)

根据答案的提供,我提出了一个解决方案,虽然不完美,但最适合我的情况。

此实现可以通过两种形式完成:

未来变化较小(仅改变'最后'):

#define push                   99
#define last                   push

#ifdef DEBUG
    #define new_instr          (1+last) 
    #define last_instruction   new_instr    
#else 
    #define last_instruction   last
#endif

OR

清除代码但在两个地方重复“推送”

#define push                   99

#ifdef DEBUG
    #define new_instr          (1+push) 
    #define last_instruction   new_instr    
#else 
    #define last_instruction   push
#endif

感谢您的帮助。

相关问题