How to cross-compile a Rust project with Cargo

Cargo builds each Rust package for a target triple, and that triple controls the CPU, operating system, vendor, and ABI expected by the finished artifact. Cross-compiling matters when the build host is not the same environment that will run the binary or module.

Rustup supplies the target's Rust standard library, while Cargo's --target flag sends build output into a target-named directory. Using wasm32-wasip1 keeps the first cross build focused on Cargo and rustup because the target produces a .wasm artifact without requiring a separate target C linker.

Native targets can still need platform tools outside Rust, especially when crates link C code or when the target uses another system linker. Keep the target triple, linker or SDK, and final artifact path tied together so a successful build represents the environment you plan to deploy.

Steps to cross-compile a Rust project with Cargo:

  1. Build or run the project for the host target first.
    $ cargo run
       Compiling demo-cli v0.1.0 (/work/demo-cli)
        Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.34s
         Running `target/debug/demo-cli`
    Hello, world!

    Run this from the directory that contains Cargo.toml. If the host build fails, fix that before adding a cross target.

  2. Add the Rust standard library for the target.
    $ rustup target add wasm32-wasip1
    info: downloading component rust-std

    Replace wasm32-wasip1 with another value from rustc --print target-list when your deployment target differs.

  3. Build the package for the target triple.
    $ cargo build --target wasm32-wasip1
       Compiling demo-cli v0.1.0 (/work/demo-cli)
        Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.12s

    Native targets such as x86_64-unknown-linux-musl, aarch64-unknown-linux-gnu, or mobile targets can need a target linker, C library, SDK, or Cargo target.<triple>.linker setting in addition to the Rust standard library.

  4. Check the target-specific artifact path.
    $ ls target/wasm32-wasip1/debug/demo-cli.wasm
    target/wasm32-wasip1/debug/demo-cli.wasm

    Debug artifacts stay under target/wasm32-wasip1/debug. Release artifacts from cargo build --release --target wasm32-wasip1 use target/wasm32-wasip1/release.