基于另一个#define的C#宏定义错误

3

我的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


阅读此内容 - Jabberwocky
你应该尝试启用“生成预处理文件”选项(/P),以查看发生了什么。 - 001
也许 __COUNTER__ 可以帮助你。 - Daniel
3个回答

5

首先,您不能两次定义同一个宏。如果需要替换宏,您需要先使用#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

代码不工作因为我真的需要tag2...当前:#define tag3 99 #define tag1 tag3 #ifdef DEBUG #define tag_help (1+tag1) #define tag2 tag_help #undef tag1 #define tag1 tag_help #endif - mfabruno
@BrunoMiguel,那也行不通,原因我已经试着解释过了。如果你需要tag2,只需使用我的代码并添加#define tag2 (tag1_val+1)即可。 - Lundin
我将编辑问题以考虑所有变量。因为我真正想要的是基于最后一个标签使tag1成为动态的。 - mfabruno

1
如果你只需要一些整数常量的符号名称,你可以像这样在一个enum中定义它们:
enum {
    push = 99,
#ifdef DEBUG
    new_instr,
#endif
    last_plus_1,
    last_instr = last_plus_1 - 1
};

如果定义了DEBUGnew_instr将会是100,last_plus_1将会是101,last_instr将会比last_plus_1小1;如果未定义DEBUGnew_instr将会是100,last_plus_1将会是100,last_instr将会比last_plus_1小1。

0
根据提供的答案,我想出了一个解决方案,虽然不完美,但最适合我的情况。
这个实现可以有两种形式:
未来更少的更改(只更改“last”):
#define push                   99
#define last                   push

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

代码清晰但在两个地方重复使用了'push'

#define push                   99

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

感谢您的帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接