3

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)
Eugene Lim
  • 269
  • 3
  • 15

1 Answers1

6

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

Community
  • 1
  • 1
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382