🎓 A1Learner
🔍
0 of 149 lessons completed

Rust Cross-Compilation

Cross-compilation means building a program for a machine unlike the build machine. Rust makes cross-compilation a two-step job.

See what you can already build for

The installed list is short at first: your host target, and any targets you added earlier:

rustup target list --installed

Add a target

rustup downloads the standard library for the new target. A simple program needs nothing else:

rustup target add x86_64-unknown-linux-musl

Build for the new target

The --target flag names the destination. Your normal build stays untouched:

cargo build --target x86_64-unknown-linux-musl

Each target gets its own folder

The cross-built program lands in a folder named by its triple. Your host build sits one folder over:

target/x86_64-unknown-linux-musl/debug/xapp
target/debug/xapp

Make the target the default

A project config file can name the target once. Then plain cargo build aims there:

// .cargo/config.toml
[build]
target = "x86_64-unknown-linux-musl"

The musl build stands alone

A musl binary carries everything it needs, so it runs on any Linux of the same architecture. This is the test program from the folders above, running after its cross build:

fn main() {
    println!("hello from xapp");
}

Example

// One-time setup:
// rustup target add x86_64-unknown-linux-musl
// Build for the other system:
// cargo build --target x86_64-unknown-linux-musl
fn main() {
    println!("hello from xapp");
}

Key points

  • Target triple: the name of one platform, in the shape architecture-vendor-system, like x86_64-unknown-linux-gnu
  • Use rustup target add <triple> to install the standard library for a target.
  • Without it, Cargo cannot build for that target
  • Use cargo build --target <triple> to build for it.
  • The result lands in target/<triple>/, beside your normal build
  • Building is not running.
  • cargo run and cargo test for a foreign target need something extra.
  • They need a machine, an emulator, or a configured runner for that system.
  • A crate that links a C library needs that library built for the target too.
  • Pure Rust crates cross-compile with no extra parts
  • In cross-compilation, the build machine differs from the machine that runs the program.

In this example, the program is completely ordinary. All the cross work lives in the two commands above it. The first installs the musl standard library. The second builds this program for musl Linux. The finished binary waits in target/x86_64-unknown-linux-musl/debug/. It is statically linked, so it runs on any x86-64 Linux, including this machine.

Note

Your own system is a target too — the host target.

Cross-compilation is only the case where the target differs from the host.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

You develop on Linux and must ship a program for a machine with a different architecture. What are the first two steps?