clang链接成动态库 - ShenYj/ShenYj.github.io GitHub Wiki

clang链接成动态库

  • 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.dylib"
    clang -dynamiclib \ # 链接成动态库
    -target x86_64-apple-macos12.1 \
    -fobjc-arc \
    -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.1.sdk \
    TestExample.o -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 脚本的路径

⚠️ **GitHub.com Fallback** ⚠️