extern function with macro

走远了吗. 提交于 2019-12-23 17:16:24

问题


Im having a linker problem in Objective C when i attempt to do a marco with a extern function. Any idea why?

Header file
To assist in doing comparison with the device version

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 file

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

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

Linker Error:

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)

回答1:


The problem is not caused by the macro definition.

The getOperatingSystemVerisonCode() function is defined in a ".mm" file and therefore compiled as Objective-C++. In particular, the function name is mangled as a C++ function. But when referenced from (Objective-)C sources, the unmangled name is expected.

You have two options to solve the problem:

  • Rename the ".mm" file to ".m", so that it is compiled as an Objective-C file.

  • In the header file where the function is declared, add the extern "C" declaration to enforce C linkage even in an (Objective-)C++ file:

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

For more information about mixing C and C++, see for example

  • Combining C++ and C - how does #ifdef __cplusplus work?


来源:https://stackoverflow.com/questions/23882780/extern-function-with-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!