【问题标题】:C #define based in another #define errorC #define 基于另一个 #define 错误
【发布时间】:2016-04-08 14:04:13
【问题描述】:

所以我的 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,任何帮助将不胜感激。

谢谢! 巴

【问题讨论】:

  • read this
  • 您应该尝试启用“生成预处理文件”选项 (/P) 以查看发生了什么。
  • 也许__COUNTER__ 会帮助你。

标签: c c-preprocessor


【解决方案1】:

首先,您不能将同一个宏定义两次。如果需要替换宏,首先要#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
  • @BrunoMiguel 这也行不通,因为我试图解释的原因。现在,如果您需要 tag2,只需使用我的代码并添加 #define tag2 (tag1_val+1)
  • 我将编辑问题以考虑所有变量。因为我真正想要的是 tag1 基于最后一个标签是动态的......
【解决方案2】:

如果您想要的只是整数常量的一些符号名称,您可以像这样在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 将小于 1 last_plus_1.

【讨论】:

    【解决方案3】:

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

    这个实现可以有两种形式:

    未来的变化更少(只改变'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
    

    感谢您的帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      相关资源
      最近更新 更多