【问题标题】:Preprocessor #if in Objective C misevaluating?Objective C中的预处理器#if错误评估?
【发布时间】:2018-08-30 19:18:51
【问题描述】:

我有代码说(字面意思):

#define BUILD_PLATFORM ios
#if BUILD_PLATFORM==macos
#import <AppKit/AppKit.h>
#elif BUILD_PLATFORM==ios
#import <UIKit/UIKit.h>
#endif

但是,当我尝试构建项目时,它仍然尝试导入 AppKit/AppKit.h,导致找不到标头的错误。

我做错了什么?

【问题讨论】:

标签: objective-c c-preprocessor


【解决方案1】:

C 预处理器的问题在于它只能比较数字。 iosmacos 都是无法真正比​​较的文字。您必须先定义它们,例如

#define ios 1
#define macos 2

但是,如果您这样做,请使用不会与您的代码冲突的更好的名称。

如果您想知道 Apple 是如何做到这一点的,请查看适用于 iOS 和 Mac OS 的文件“Availability.h”,这可能是您应该使用的东西,例如:

#ifdef __MAC_OS_X_VERSION_MAX_ALLOWED
#import <AppKit/AppKit.h>
#else
#import <UIKit/UIKit.h>
#endif

【讨论】:

    【解决方案2】:

    使用 CMake 时,以下工作:

    CMakeLists.txt:

    add_definitions(-DPLATFORM=${PLATFORM})  # Set to the target platform
    

    目标 C:

    #if defined(PLATFORM_macos)
    #import <AppKit/AppKit.h>
    #elif defined(PLATFORM_ios)
    #import <UIKit/UIKit.h>
    #endif
    

    【讨论】:

      猜你喜欢
      • 2017-04-19
      • 1970-01-01
      • 1970-01-01
      • 2012-06-08
      • 2016-05-17
      • 1970-01-01
      • 2016-08-21
      • 2015-09-13
      • 1970-01-01
      相关资源
      最近更新 更多