Cross-Compiling Rust in a DevContainer
You develop on one platform but ship Rust binaries for others. This page cross-compiles from a devcontainer by adding the rustup target and the matching linker, covering the pure-Rust case and the C-dependency case.
Prerequisites
You need a Rust devcontainer and the target triple you build for.
- A Rust toolchain in the container.
- The
rustuptarget triple you want (e.g.aarch64-unknown-linux-gnu). - A cross linker for that target if you link C.
Step-by-Step Implementation
- Add the target triple.
rustup target add aarch64-unknown-linux-gnu
- Install a cross linker for that target.
apt-get install -y gcc-aarch64-linux-gnu
- Point cargo at the linker.
# .cargo/config.toml
[target.aarch64-unknown-linux-gnu]
linker = "aarch64-linux-gnu-gcc"
- Build for the target and verify.
cargo build --target aarch64-unknown-linux-gnu && file target/aarch64-unknown-linux-gnu/debug/app
Common Pitfalls
Cross-compile failures are a missing target or the wrong linker.
| Symptom | Root Cause | Remediation |
|---|---|---|
| error: target not installed | rustup target missing | rustup target add |
| linker not found | No cross linker for the target | Install gcc- |
| links against host libs | cargo used the host linker | Configure the target's linker |
| Runs on host only | Built for the host triple | Pass --target |
Conclusion
Cross-compiling Rust is rustup target add plus, when C is involved, a matching cross linker configured in .cargo/config.toml. Pure-Rust targets need only the target; C-linked ones need the linker. Either way one devcontainer builds for many platforms.
FAQ
How do I build a Rust binary for a different platform?
Add the target with rustup target add <triple> and build with cargo build --target <triple>. For pure-Rust programs that is all you need — the toolchain produces a binary for the target from your dev container.
Why does cross-compilation fail when my crate uses C?
Because linking C requires a cross linker for the target, and cargo defaults to the host linker. Install the cross toolchain (e.g. gcc-aarch64-linux-gnu) and point cargo at it in .cargo/config.toml under the target section.
Can I cross-compile to musl for static binaries?
Yes — add the musl target (e.g. x86_64-unknown-linux-musl) and build against it for a static binary with no glibc dependency. It's a common way to produce portable Rust binaries from a devcontainer for container distribution.
Related
- Up to Rust DevContainer Environment with Cargo — the overview of Rust setup.
- Caching the Cargo Registry and Target in a DevContainer — caching across target builds.
- Cross-Compiling Go Binaries Inside Containers — the Go equivalent.