【问题标题】:Conditional compilation with ifndef and || doesn't catch second case使用 ifndef 和 || 进行条件编译没有抓住第二种情况
【发布时间】:2013-09-03 08:21:48
【问题描述】:

当设置了两个定义中的一个或两个时,我正在尝试禁用自动崩溃日志报告:DEBUG 用于我们的调试版本,INTERNATIONAL 用于国际版本。但是,当我尝试在 #ifndef 情况下执行此操作时,我收到警告 Extra tokens at end of #ifndef directive 并使用定义的 DEBUG 运行将触发 Crittercism。

#ifndef defined(INTERNATIONAL) || defined(DEBUG)
    // WE NEED TO REGISTER WITH THE CRITTERCISM APP ID ON THE CRITTERCISM WEB PORTAL
    [Crittercism enableWithAppID:@"hahayoudidntthinkidleavetherealonedidyou"];
#else
    DDLogInfo(@"Crash log reporting is unavailable in the international build");

    // Since Crittercism is disabled for international builds, go ahead and
    // registers our custom exception handler. It's not as good sadly
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    DDLogInfo(@"Registered exception handler");
#endif

这个真值表显示了我的期望:

INTL defined | DEBUG defined | Crittercism Enabled
     F       |      F        |    T
     F       |      T        |    F
     T       |      F        |    F
     T       |      T        |    F

这在之前只是 #ifndef INTERNATIONAL 时有效。我也尝试过不使用 defined(blah) 并在整个语句周围加上括号(分别是相同的警告和错误)。

如何从编译器获得我想要的行为?

【问题讨论】:

    标签: ios objective-c conditional-compilation


    【解决方案1】:

    你想要:

    #if !defined(INTERNATIONAL) && !defined(DEBUG)
        // neither defined - setup Crittercism
    #else
        // one or both defined
    #endif
    

    或者你可以这样做:

    #if defined(INTERNATIONAL) || defined(DEBUG)
        // one or both defined
    #else
        // neither defined - setup Crittercism
    #endif
    

    【讨论】:

    • 这解决了它,谢谢。你知道#ifndef 是否有一些东西可以防止复杂的条件?
    • 您不能将#ifdef#ifndefdefined() 结合使用。而#ifdef#ifndef 只能检查一个值——#ifndef INTERNATIONAL
    【解决方案2】:

    我刚刚找到了一篇Conditional Compilation 的帖子,可以更好地解释#if/#elif#ifdef/#ifndef从语法层面的区别:

    • #if constant-expression newline
    • #ifdef identifier newline
    • #ifndef identifier newline
    • #else newline
    • #elif constant-expression newline
    • #endif newline

    所以这里我们可以看到#ifndef 后面必须跟“标识符”,这通常是#define 指令定义的宏,或者@rmaddy 表示“单个值”。

    但是if后面可以跟'constant-expression',这样就可以使用条件表达式defined(INTERNATIONAL) || defined(DEBUG)或者!defined(INTERNATIONAL) && !defined(DEBUG)了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      • 2013-09-10
      • 2014-07-06
      • 2011-03-27
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      相关资源
      最近更新 更多