You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Swift Package生成适配iOS(模拟器/真机)的静态库?

问题:Swift Package指定iOS架构生成静态库

我有一个Swift Package,希望将其集成到CI流程中并生成静态库。执行swift build命令后生成的静态库是MacOS arm64架构,无法用于iOS项目,请问如何指定iOS(模拟器/真机)架构来生成可用的静态库?

我的Package.swift代码如下:

import PackageDescription

let package = Package(
    name: "CMyLibrary",
    platforms: [
        .iOS(.v11),
        .watchOS(.v6),
    ],
    products: [
        // Products define the executables and libraries a package produces, and make them visible to other packages.
        .library(
            name: "CMyLibrary",
            type: .static,
            targets: ["CMyLibrary"]),
    ],
    dependencies: [],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages this package depends on.
        .target(
            name: "CMyLibrary",
            dependencies: ["CWolfCrypt", "CWolfSsl"],
            path: "Sources/CMyLibrary",
            cSettings: [
                .headerSearchPath("./"),
            ]),
        .target(
            name: "CWolfCrypt",
            dependencies: [],
            path: "Sources/CWolfCrypt",
            cSettings: [
                .headerSearchPath("./"),
            ]),
        .target(
            name: "CWolfSsl",
            dependencies: ["CWolfCrypt"],
            path: "Sources/CWolfSsl"),
    ],
    cLanguageStandard: .c11
)
解决方案

1. 编译iOS真机版本(arm64架构)

直接用swift build指定iOS真机SDK和架构,命令如下:

swift build -sdk $(xcrun --sdk iphoneos --show-sdk-path) -arch arm64 -c release

这里xcrun --sdk iphoneos --show-sdk-path会自动获取当前系统的iOS真机SDK路径,确保编译产物适配iOS真机环境。

2. 编译iOS模拟器版本

根据你的Mac芯片类型,选择对应架构的编译命令:

  • Intel芯片Mac(模拟器架构x86_64):
swift build -sdk $(xcrun --sdk iphonesimulator --show-sdk-path) -arch x86_64 -c release
  • Apple Silicon芯片Mac(模拟器架构arm64):
swift build -sdk $(xcrun --sdk iphonesimulator --show-sdk-path) -arch arm64 -c release

3. 生成通用静态库(同时支持真机+模拟器)

如果需要一个能同时在真机和模拟器上使用的静态库,可以用lipo命令合并两个架构的产物:

  1. 先分别编译好真机和模拟器版本的静态库
  2. 找到编译后的静态库路径:真机版本在.build/arm64-apple-ios/release/下,模拟器版本在.build/arm64-apple-ios-simulator/release/下(对应你的架构)
  3. 执行合并命令:
lipo -create \
.build/arm64-apple-ios/release/libCMyLibrary.a \
.build/arm64-apple-ios-simulator/release/libCMyLibrary.a \
-output libCMyLibrary-universal.a

4. CI流程集成要点

在CI脚本里可以按以下流程实现自动化:

  • 依次编译真机、模拟器版本的静态库
  • 用lipo合并生成通用库
  • 将最终的静态库和对应的头文件打包,输出到指定目录,方便后续集成到iOS项目中

内容的提问来源于stack exchange,提问作者Anton Unt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:30:59