Xcode里-ObjC, -all_load, -force_load
之所以使用该标志,和Objective-C的一个重要特性:类别(category)有关。根据这里的解释,Unix的标准静态库实现和Objective-C的动态特性之间有一些冲突:Objective-C没有为每个函数(或者方法)定义链接符号,它只为每个类创建链接符号。这样当在一个静态库中使用类别来扩展已有类的时候,链接器不知道如何把类原有的方法和类别中的方法整合起来,就会导致你调用类别中的方法时,出现"selector not recognized",也就是找不到方法定义的错误。为了解决这个问题,引入了-ObjC标志,它的作用就是将静态库中所有的和对象相关的文件都加载进来。
本来这样就可以解决问题了,不过在64位的Mac系统或者iOS系统下,链接器有一个bug,会导致只包含有类别的静态库无法使用-ObjC标志来加载文件。变通方法是使用-all_load 或者-force_load标志,它们的作用都是加载静态库中所有文件,不过all_load作用于所有的库,而-force_load后面必须要指定具体的文件。
明白了这些,我就清楚,这个第三方库中一定是定义了一些类别来扩着已有类,打开头文件,发现果然如此。
#import
@interface MyStaticLibraryDemo : NSObject
/// 加法
- (int)addMethodByFirst:(int)theFirst andSecond:(int)theSecond;
/// 减法
- (int)SubMethodByFirst:(int)theFirst andSecond:(int)theSecond;
@end
#import "MyStaticLibraryDemo.h"
@implementation MyStaticLibraryDemo
/// 加法
- (int)addMethodByFirst:(int)theFirst andSecond:(int)theSecond{
return (theFirst+theSecond);
}
/// 减法
- (int)SubMethodByFirst:(int)theFirst andSecond:(int)theSecond{
return (theFirst-theSecond);
}
@end
bogon:~ zhangzhen$ cd /Users/zhangzhen/Library/Developer/Xcode/DerivedData/MyStaticLibraryDemo-ciwnhcsbqgclkododazbmbmtdlfp/Build/Products/Release-iphoneos
bogon:Release-iphoneos zhangzhen$ lipo -info libMyStaticLibraryDemo.a
Architectures in the fat file: libMyStaticLibraryDemo.a are: armv7 armv7s arm64
bogon:~ zhangzhen$ cd /Users/zhangzhen/Library/Developer/Xcode/DerivedData/MyStaticLibraryDemo-ciwnhcsbqgclkododazbmbmtdlfp/Build/Products/Release-iphonesimulator
bogon:Release-iphonesimulator zhangzhen$ lipo -info libMyStaticLibraryDemo.a
Architectures in the fat file: libMyStaticLibraryDemo.a are: i386 x86_64
MyStaticLibraryDemo *myLibrary=[[MyStaticLibraryDemo alloc] init];
int result= [myLibrary addMethodByFirst:5 andSecond:5];
NSLog(@"Result:%d",result);
result=[myLibrary SubMethodByFirst:10 andSecond:5];
NSLog(@"Result:%d",result);
ld: warning: ignoring file /Users/XXXX/Documents/MyLibraryTest/MyLibraryTest/MyLibrary/libMyStaticLibraryDemo.a, missing required architecture i386 in file/Users/XXXX/Documents/MyLibraryTest/MyLibraryTest/MyLibrary/libMyStaticLibraryDemo.a (3 slices)
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_MyStaticLibraryDemo", referenced from:
objc-class-ref in AppDelegate.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see invocation)
bogon:~ zhangzhen$ lipo -create /所在路径/Release-iphoneos/libMyStaticLibraryDemo.a /所在路径/Release-iphonesimulator/libMyStaticLibraryDemo.a -output /Users/zhangzhen/Desktop/libUniversal.a
bogon:~ zhangzhen$