可汗的博客·交叉编译 Swift

2025 年 3 月 29 日,介绍了在不同平台上交叉编译 Swift 的多种方法,包括在构建 Discord 机器人和 Bluesky 机器人时的探索:

  • Link Embed Bot(链接嵌入机器人):为 Discord 制作的小型链接嵌入机器人,使用DiscordBM包实现,目标是 24/7 运行并处理事件,需下载图片,利用家中服务器(8GB 内存)满足需求。开发在 Mac 上,要在 Gentoo 机器上运行需使用静态 Linux SDKs。

    • Method 1: Static Linux SDK(静态 Linux SDK 方法)

      • Step 1: Install the Open-Source Toolchain (Not Xcode)(安装开源工具链(非 Xcode)):需从Swift.org安装开源 Swift 工具链,可使用Swiftly工具或下载安装包,运行swift时仍使用 Xcode 的 Swift 版本,需用xcrun运行刚安装的工具链,如xcrun --toolchain swift swift build -c release
      • Step 2: Install the SDK(安装 SDK):通过 Swift 的安装页面获取 URL 和校验和来下载和安装 SDK,可用swift sdk install <URL-or-filename-here> [--checksum <checksum-for-archive-URL>],列出已安装的 SDK 用swift sdk list,更多选项用swift sdk --help,无论使用哪种工具链安装,SDK 都安装在同一位置。
      • Step 3: Compile using the SDK(使用 SDK 编译):确保使用开源工具链,通过xcrun运行,如xcrun --toolchain swift swift build --swift-sdk x86_64-swift-linux-musl -c release
  • Captain, It's Wednesday(船长,星期三):在Bluesky上的captainitswednesday.com机器人项目,使用ATProtoKit Swift 库,每天 9 点发布帖子,遇到使用静态 Linux SDKs 时的编译器崩溃问题,需回到原始的交叉编译方法——Docker。

    • Method 2: Docker Containers(Docker 容器方法)

      • Step 1: Download the target Docker container(下载目标 Docker 容器):官方 Swift 指南提到的swift:bionic容器已过时,建议下载swift:latest(Ubuntu 容器,预安装 Swift),也可根据需要使用其他 Linux 版本,如docker pull swift:latest --platform linux/amd64
      • Step 2: Compile & Copy Out(编译并复制输出):使用 Docker 运行容器,挂载当前目录到容器的/workspace文件夹并设置为工作目录,在容器中运行 bash 命令编译 Swift 包、删除.build/install目录内容并将编译输出复制到该目录,如docker run --platform linux/amd64 --rm -v "$PWD:/workspace" -w /workspace swift:latest /bin/bash -cl '\ swift build -c release --static-swift-stdlib && rm -rf.build/install && mkdir -p.build/install && cp -P.build/release/CaptainItsWednesday.build/install/',注意修改cp步骤的路径,还可添加剥离步骤以减少最终可执行文件大小。
      • Step 3: Profit(获利):将整个步骤放在名为deploy.sh的脚本中,然后使用scp将结果可执行文件复制到本地服务器,如scp.build/install/CaptainItsWednesday [email protected]:/home/khan/,可运行file检查目标平台。
  • Final Thoughts(最终思考):Swift 的交叉编译能力有了很大进步,虽仍有工具链等方面的困惑,但对 Swift 的发展充满期待,继续享受用 Swift 编程的乐趣。
阅读 9
0 条评论