【问题标题】:extern function with macro带有宏的外部函数
【发布时间】:2014-05-27 06:47:55
【问题描述】:

当我尝试使用外部函数执行 marco 时,我在 Objective C 中遇到了链接器问题。知道为什么吗?

头文件
协助与设备版本进行比较

extern NSString* getOperatingSystemVerisonCode();

#if TARGET_OS_IPHONE // iOS
#define DEVICE_SYSTEM_VERSION                       [[UIDevice currentDevice]      systemVersion]
#else // Mac
#define DEVICE_SYSTEM_VERSION                       getOperatingSystemVerisonCode()
#endif

#define COMPARE_DEVICE_SYSTEM_VERSION(v)            [DEVICE_SYSTEM_VERSION compare:v options:NSNumericSearch]
#define SYSTEM_VERSION_EQUAL_TO(v)                  (COMPARE_DEVICE_SYSTEM_VERSION(v) == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              (COMPARE_DEVICE_SYSTEM_VERSION(v) == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  (COMPARE_DEVICE_SYSTEM_VERSION(v) != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 (COMPARE_DEVICE_SYSTEM_VERSION(v) == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     (COMPARE_DEVICE_SYSTEM_VERSION(v) != NSOrderedDescending)

.mm 文件

NSString* getOperatingSystemVerisonCode()
{
    /*
     [[NSProcessInfo processInfo] operatingSystemVersionString]
     */
    NSDictionary *systemVersionDictionary =
    [NSDictionary dictionaryWithContentsOfFile:
     @"/System/Library/CoreServices/SystemVersion.plist"];

    NSString *systemVersion =
    [systemVersionDictionary objectForKey:@"ProductVersion"];
    return systemVersion;
}

链接器错误:

Undefined symbols for architecture x86_64:
  "_getOperatingSystemVerisonCode", referenced from:
      -[Manager isFeatureAvailable] in Manager.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

【问题讨论】:

    标签: objective-c macros extern


    【解决方案1】:

    问题不是宏定义引起的。

    getOperatingSystemVerisonCode() 函数在“.mm”文件中定义,因此 编译为 Objective-C++。特别是,函数名称被修改为 C++ 函数。 但是,当从 (Objective-)C 源代码中引用时,需要使用未修改的名称。

    你有两种选择来解决这个问题:

    • 将“.mm”文件重命名为“.m”,以便编译为Objective-C文件。

    • 在声明函数的头文件中,添加 extern "C" 声明以强制 C 链接,即使在 (Objective-)C++ 文件中:

      #ifdef __cplusplus
      extern "C" {
      #endif
      
      NSString* getOperatingSystemVerisonCode();
      
      #ifdef __cplusplus
      }
      #endif
      

    有关混合 C 和 C++ 的更多信息,请参阅示例

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-04
      • 2021-07-12
      • 2018-10-12
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多