文章

Rust 多平台编译

在执行对 rust 二进制文件内存分析时, 提示找不到动态库 .so, 因此需要静态编译 rust 二进制文件

安装新平台支持

1
rustup target add x86_64-unknown-linux-musl

使用下述命令查看当前系统安装的所有 target

1
rustup target list --installed

查看所有的 rust target, 包括目前还未安装的

1
rustup target list

比如对于输出 x86_64-unknown-linux-musl, 可以这样理解

1
<架构>-<厂商>-<系统>-<ABI>

对于 x86_64-unknown-linux-musl: x86_64:目标架构是 64 位 x86(常见的服务器架构) unknown:厂商未知(通常没啥实际影响) linux:目标操作系统是 Linux musl:使用的是 musl libc(一种小巧、安全、静态链接的 C 运行时库) 👉 它和 x86_64-unknown-linux-gnu 的区别就在于: gnu 是用的 glibc,体积更大、依赖动态链接 musl 支持静态链接,生成的 binary 可以 在任何 Linux 上运行,更适合部署

在执行 cargo build 的时候可以选择目标平台

1
cargo build --release --target x86_64-unknown-linux-musl

关于 musl 完全静态编译,可以参考 https://rustwiki.org/zh-CN/edition-guide/rust-2018/platform-and-target-support/musl-support-for-fully-static-binaries.html

在 Mac 上执行跨平台的 build 的时候,可能会遇到报错

1
2
3
4
Compiling paste v1.0.15
warning: ring@0.17.14: Compiler family detection failed due to error: ToolNotFound: failed to find tool "musl-gcc": No such file or directory (os error 2)
warning: ring@0.17.14: Compiler family detection failed due to error: ToolNotFound: failed to find tool "musl-gcc": No such file or directory (os error 2)
error: failed to run custom build command for `ring v0.17.14`

cross 是社区构建的专门用于 Rust 跨平台交叉构建的封装工具,它内置了所有目标平台的编译工具链(包括 musl-gcc),无需你手动配置。

1
2
cargo install cross

但是 cross build 在 mac 上是依赖 x86 的 toolchain 的,看起来还需要 ubuntu docker 可以使用下面的命令查看已经安装的 二进制路径

1
cargo install --list

还需要搞清楚 rustup toolchain、target 之间的关系

关于如何编译 musl 版本的 rust 代码,可以参考 https://blog.biofan.org/2019/08/rust-static-build-with-musl/

本文由作者按照 CC BY 4.0 进行授权