Rust Cross Compile

交叉编译Linux平台程序

环境配置

  • rustup target add x86_64-unknown-linux-musl - 安装工具链
  • brew install filosottile/musl-cross/musl-cross

编译程序

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

交叉编译Windows平台程序

环境配置

  • rustup target add x86_64-pc-windows-gnu
  • brew install mingw-w64

编译程序

1
cargo build --release --target x86_64-pc-windows-gnu

工具链配置

1
2
3
4
5
6
# 在项目目录下.cargo/config 或 ~/.cargo/config 中配置如下内容
[target.x86_64-unknown-linux-musl]
linker = "x86_64-linux-musl-gcc"
[target.x86_64-pc-windows-gnu]
linker = "x86_64-w64-mingw32-gcc"
ar = "x86_64-w64-mingw32-gcc-ar"

通过LTO缩减程序体积

1
2
3
4
5
6
7
8
9
# 在Cargo.toml 中添加如下配置
[profile.release]
opt-level = "z" # Optimize for size.
lto = true # Enable Link Time Optimization
codegen-units = 1 # Reduce number of codegen units to increase optimizations.
panic = "abort" # Abort on panic
strip = true
# or strip = "symbols" # Strip symbols from binary

Reference