如何在Mac上为Linux交叉编译Rust程序

摘译自: Rust on Lambda, 其它参考: Cross-compiling a simple Rust web appHow to Cross-Compile from Mac to Linux on RustMUSL support for fully static binariesCross-compile and link a static binary on macOS for Linux with cargo and rust

目标是创建 x86_64-unknown-linux-musl 平台的应用程序,通过静态连接musl, 不再依赖glibc库。

在Linux上操作比较简单,执行下面的命令:

1
2
rustup target add x86_64-unknown-linux-musl # First time only
cargo build --release --target x86_64-unknown-linux-musl

如果在OSX运行,会报下面的错误:

1
Internal error occurred: Failed to find tool. Is `musl-gcc` installed?

在macOS使用musl可以通过安装musl-cross-make实现:

1
brew install FiloSottile/musl-cross/musl-cross

你还需要创建musl-gcc:

1
ln -s /usr/local/bin/x86_64-linux-musl-gcc /usr/local/bin/musl-gcc

你还需要设置linker, 创建一个文件.cargo/config,增加下面的两行:

1
2
[target.x86_64-unknown-linux-musl]
linker = "x86_64-linux-musl-gcc"

然后运行下面的命令进行交叉编译:

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