Cross-Compilation with Cargo and cross
Advanced15 min
Cross-compile Rust binaries for different operating systems and architectures using cargo and the cross tool.
Prerequisites
- -Rust toolchain installed via rustup
- -Docker installed (for cross tool)
Steps
1
List available targets
View all compilation targets supported by the Rust toolchain.
$ rustup target list | grep -E '(linux|darwin|windows|wasm)'
2
Add a target and compile natively
Install a target and cross-compile using cargo build directly.
$ rustup target add x86_64-unknown-linux-musl && cargo build --release --target x86_64-unknown-linux-musl
The musl target produces a fully static binary that works on any Linux distribution.
3
Install the cross tool
Install cross, which uses Docker containers with pre-configured toolchains for hassle-free cross-compilation.
$ cargo install cross --git https://github.com/cross-rs/cross
4
Cross-compile for Linux ARM64
Build for aarch64 Linux using cross, which handles the toolchain automatically.
$ cross build --release --target aarch64-unknown-linux-gnu
5
Build for multiple targets with a script
Automate cross-compilation for all desired platforms.
$ for target in x86_64-unknown-linux-musl aarch64-unknown-linux-gnu x86_64-apple-darwin aarch64-apple-darwin x86_64-pc-windows-gnu; do echo "Building $target" && cross build --release --target $target; done
macOS targets may not work with cross unless you have the appropriate linker. Use native compilation on macOS for darwin targets.
Full Script
FAQ
Discussion
Loading comments...