Cross Compilation Basics
Why cross compilation matters in production
In production, you should not build software on the production server. Builds must be deterministic, repeatable, and created in a controlled environment such as CI. Cross compilation allows you to produce binaries for Linux targets even if you develop on macOS or Windows. This reduces drift between environments and avoids hidden runtime surprises.
Production goals at this level
- Deterministic builds: same commit produces the same binary.
- No production compilation: production servers only run artifacts.
- Explicit target: build for the exact OS and architecture you deploy to.
- Small attack surface: avoid installing build tools on runtime machines.
Know your target triple
Rust builds for specific targets. For example:
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- aarch64-unknown-linux-gnu
In containerized Linux environments, musl targets are often useful because they can produce more portable static binaries.
List available targets
rustup target list
Add a Linux target
rustup target add x86_64-unknown-linux-gnu
Build a release binary
Always use release mode for production artifacts. Debug builds are slower and larger.
cargo build --release --target x86_64-unknown-linux-gnu
The resulting binary will be located under:
target/x86_64-unknown-linux-gnu/release/your_binary
Using musl for static binaries
Static binaries are often easier to ship in minimal containers because they reduce dependency on system libraries.
rustup target add x86_64-unknown-linux-musl cargo build --release --target x86_64-unknown-linux-musl
Verify the binary
Before shipping, confirm architecture and linkage.
file target/x86_64-unknown-linux-gnu/release/your_binary
Production mindset: build once, run many
The artifact built in CI should be the same artifact deployed to staging and production. Avoid rebuilding separately per environment. This ensures you are debugging the same binary everywhere.
CI integration pattern
A minimal CI flow:
- Checkout code
- Install target
- cargo build --release --target
- Archive artifact
- Publish artifact or container
Common mistakes
- Building on production servers.
- Mixing debug and release artifacts.
- Not specifying target explicitly in CI.
- Relying on system libraries that differ between environments.
Operational checklist
- Release builds are reproducible.
- Artifacts are created in CI.
- Production servers only run prebuilt binaries.
What comes next
Now that we can produce release binaries, the next step is packaging them safely into containers for consistent runtime environments.