C #define based in another #define 错误
C #define based in another #define error
所以我的 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,任何帮助将不胜感激。
谢谢!
巴
首先,同一个宏不能定义两次。如果你需要替换一个宏,你首先得#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
根据提供的答案,我想出了一个解决方案,虽然不完美但最适合我的情况。
此实现可以通过两种形式完成:
以后少改(只改'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
感谢您的帮助。
如果您想要的只是整数常量的一些符号名称,您可以在 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
undefined), last_instr
将比 last_plus_1
.
小一
所以我的 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,任何帮助将不胜感激。
谢谢! 巴
首先,同一个宏不能定义两次。如果你需要替换一个宏,你首先得#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
根据提供的答案,我想出了一个解决方案,虽然不完美但最适合我的情况。
此实现可以通过两种形式完成:
以后少改(只改'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
感谢您的帮助。
如果您想要的只是整数常量的一些符号名称,您可以在 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
undefined), last_instr
将比 last_plus_1
.