【问题标题】:Using #define to define and #if defined to see if it is defined用#define定义,#if定义看是否定义
【发布时间】:2010-11-04 04:33:16
【问题描述】:

gcc 4.4.4 c89

我正在尝试定义一些东西。如果它被定义了我想做一些事情,否则我想做一些不同的事情。

#define PARSE_STRING
    for(i = 0; i < NUMBER_OF_STRINGS; i++) {
#if defined (PARSE_STING)
    /* run code for parsing the strings */
#else
    /* run code that doesn't parse the strings
    }
#endif

当我在我的函数中尝试上述代码时,我似乎在我的代码中的其他地方遇到了其他错误。但是,如果我将 #define PARSE_STRING 注释掉,它就可以编译。我只是想知道我是否需要#define PARSE_STRING

非常感谢您的任何建议,

====== 使用更新的解决方案进行编辑

这样做会更好吗?

#define PARSE_STRING
    for(i = 0; i < NUMBER_OF_STRINGS; i++) {
#if defined (PARSE_STRING)
    /* run code for parsing the strings */
#elif defined (NO_PARSE_STRING)
    /* run code that doesn't parse the strings
#endif
    }

【问题讨论】:

  • 我在粘贴代码时对其进行了编辑。那只是一个错误。谢谢。
  • 我怀疑你的拼写错误迟早会刺痛你:#if defined(PARSE_STING) 应该是#if defined(PARSE_STRING)
  • RE:编辑:不,这样不好。

标签: c gcc macros c-preprocessor


【解决方案1】:

您将预处理指令的交错与函数体的开头和结尾混为一谈:

}
#endif

应该是

#endif
}

【讨论】:

  • 你是对的。 #endif 超出了 for 循环的范围。谢谢
【解决方案2】:

这是因为如果它被定义,你将不会有结束 } 这将是一个语法错误。

【讨论】:

    【解决方案3】:

    您已在其中一个条件中包含 for 循环的结束括号

    #else
      }
    #endif
    

    应该是

    #else
       //Stuff
    #endif
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多