ld链接器将静态库链接成动态库 - ShenYj/ShenYj.github.io GitHub Wiki
-
test.m
文件#import <Foundation/Foundation.h> #import "TestExample.h" int main(){ NSLog(@"testApp----"); TestExample *manager = [TestExample new]; [manager lg_test: nil]; return 0; }
-
TestExample.h
#import <Foundation/Foundation.h> @interface TestExample : NSObject - (void)lg_test:(_Nullable id)e; @end
-
TestExample.m
#import "TestExample.h" @implementation TestExample - (void)lg_test:(_Nullable id)e { NSLog(@"TestExample----"); } @end
-
脚本
echo "编译test.m --- test.o" clang -target x86_64-apple-macos12.1 \ -fobjc-arc \ -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk \ -I./dylib \ -c test.m -o test.o pushd ./dylib echo "编译TestExample.m --- TestExample.o" clang -target x86_64-apple-macos12.1 \ -fobjc-arc \ -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk \ -c TestExample.m -o TestExample.o echo "编译TestExample.o --- libTestExample.a" # 新增 >>>>>>>>>>> # Xcode (默认使用的就是 libtool 来编译静态库) -> 静态库 libtool -static -arch_only x86_64 TestExample.o -o libTestExample.a echo "编译TestExample.m --- libTestExample.dylib" ld -dylib -arch x86_64 \ -macosx_version_min 12.1 \ -syslibroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk \ -lsystem -framework Foundation \ # -lsystem: 需要系统库支撑: dylib dyld,-framework Foundation: 链接Foundation 这个动态库 libTestExample.a -o libTestExample.dylib # 新增 <<<<<<<<<<< popd echo "链接libTestExample.dylib -- test EXEC" clang -target x86_64-apple-macos12.1 \ -fobjc-arc \ -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk \ -L./dylib \ -lTestExample \ test.o -o test
目录结构:
├── build.sh ├── dylib │ ├── TestExample.h │ └── TestExample.m └── test.m
需要给脚本添加执行的权限
chmod +x 脚本的路径
静态库通过探索得知,其是目标文件的集合,而动态库和可执行文件一样,是链接后的产物,所以才能将一个静态库链接成动态库
示例中脚本处
libTestExample.a -o libTestExample.dylib
,因此直接将.o
链接成动态库同样是没问题的