【问题标题】:How to cross compile Rust across operating systems and CPU architectures?如何跨操作系统和 CPU 架构交叉编译 Rust?
【发布时间】:2022-10-05 17:15:49
【问题描述】:

我正在学习 Rust 并编写一些基本的 CLI 工具作为练习。我将我的应用程序源存储在 Github 中,使用 Github 操作生成二进制文件并通过 Github 版本发布这些二进制文件。

问题是;我不确定如何为各种目标架构和操作系统交叉编译我的 Rust 应用程序。

(为比较道歉)以前在使用 Go 时,我可以在构建命令中指定目标 CPU 架构和目标操作系统,例如:

env GOARCH=arm64 GOOS=darwin go build

在查看 Rust 中是否有等价物时,我看到指令告诉我使用虚拟化和各种其他技术进行交叉编译。

我怀疑我可能只是不擅长研究,是否有一种等效的简单方法来交叉编译 Rust 应用程序?

如果不是,为什么会这样,您能否指出我的资源来帮助我学习如何做到这一点?

  • 您需要rustup target add 想要的目标,然后使用此工具链进行编译。

标签: rust


【解决方案1】:

cross 让这变得非常容易,尤其是因为它得到了 actions-rs/cargo 的支持。

我正在使用类似的东西

name: 'Release'

on:
  push:
    tags:
      - 'v*'

env:
  CARGO_INCREMENTAL: 0

jobs:
  build:
    name: Binary
    strategy:
      fail-fast: false
      matrix:
        job:
          - { target: x86_64-unknown-linux-musl, exe: amd64-linux, os: ubuntu-latest }
          - { target: aarch64-unknown-linux-musl, exe: aarch64-linux, os: ubuntu-latest }
          - { target: armv7-unknown-linux-musleabi, exe: armv7-linux, os: ubuntu-latest }
          - { target: wasm32-wasi, exe: wasi.wasm, os: ubuntu-latest }
          - { target: x86_64-apple-darwin, exe: macos, os: macos-latest }
          - { target: x86_64-pc-windows-msvc, exe: windows.exe, os: windows-2019 }
    runs-on: ${{ matrix.job.os }}
    steps:
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          profile: minimal
          toolchain: 1.62.0
          override: true
          target: ${{ matrix.job.target }}
          components: rust-src # necessary for wasi, because there isn't a cross image for it
      - uses: actions-rs/cargo@v1
        with:
          use-cross: true
          args: --release --target=${{ matrix.job.target }} --locked
          command: build
      - name: Rename result
        run: |
          rm target/${{ matrix.job.target }}/release/name-of-binary.d
          cp target/${{ matrix.job.target }}/release/name-of-binary* name-of-binary-${{ matrix.job.exe }}
      - name: Archive production artifacts
        uses: actions/upload-artifact@v2
        with:
          name: arty
          path: name-of-binary-${{ matrix.job.exe }}

# Release artifacts in a separate step to make sure all are successfully produced and no partial release is created

my projects 之一上。

我还指定

[profile.release]
lto = "fat"
strip = "debuginfo"

在我的Cargo.toml 中使发布的文件更好一点。

值得注意的是,Rust crates 比 Go 更容易在 C/C++ 库中构建和链接,可能会调用 CMake 或更糟。交叉编译这样的 crate 可能要困难得多,如何准确地做到这一点取决于特定的 crate。

【讨论】:

  • 您如何针对 ARM MacOS?
  • 不知道。您是否尝试将aarch64-apple-darwin 设置为target?如果出现问题,为什么不发布一个 SO 问题?
猜你喜欢
  • 2020-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 1970-01-01
  • 2021-11-24
  • 1970-01-01
相关资源
最近更新 更多