TExcelTAD
Home › Cargo in Depth › build.rs: Directives & Rebuilds

build.rs: Directives & Rebuilds

A file called build.rs in the package root is a build script: a small Rust program that Cargo compiles and runs before compiling the package. It can compile C code, generate Rust source, detect the platform, or pass flags to rustc. It talks to Cargo by printing lines to standard output.

How Cargo runs it

  1. Compile build.rs (with the [build-dependencies]) for the host machine.
  2. Run it, with the package root as the working directory and a set of environment variables describing the build.
  3. Read its stdout for cargo:: directives, apply them, then compile the package.
  4. Cache the result. Next time, rerun only if the script's rerun conditions say so.

The directives

Directive Effect
cargo::rerun-if-changed=PATH rerun when this file (or anything in this directory) changes
cargo::rerun-if-env-changed=VAR rerun when this environment variable changes
cargo::rustc-env=KEY=VALUE set an env var for the crate's compilation (read with env!)
cargo::rustc-cfg=NAME / NAME="value" enable #[cfg(NAME)] in the crate
cargo::rustc-check-cfg=cfg(NAME) declare that cfg as expected (otherwise unexpected_cfgs warns)
cargo::rustc-link-lib=[KIND=]NAME link a native library (static=, dylib=)
cargo::rustc-link-search=[KIND=]PATH add a library search path
cargo::rustc-link-arg=FLAG pass a flag to the linker
cargo::warning=MESSAGE show a warning to the user
cargo::error=MESSAGE fail the build with this message
cargo::metadata=KEY=VALUE pass data to dependents' build scripts (links)

cargo:: vs cargo:. The double-colon form arrived in Rust 1.77. Before that, directives were written cargo:rustc-env=... with one colon, and anything unknown after cargo: was treated as metadata. The old form still works, but new code should use cargo::, unless the crate's MSRV is below 1.77 (Cargo refuses, as shown below). The cc crate still prints the single-colon form for compatibility, so you'll see both in real output.

Inputs: environment variables

Variable Example
OUT_DIR where the script may write files: target/debug/build/<pkg>-<hash>/out
TARGET, HOST aarch64-unknown-linux-gnu, x86_64-unknown-linux-gnu
PROFILE debug or release (the directory, not the custom profile name)
OPT_LEVEL, DEBUG the profile's settings
CARGO_CFG_TARGET_OS, CARGO_CFG_TARGET_ARCH, … the target's cfg values; use these, not cfg!() inside build.rs, which describes the host
CARGO_FEATURE_<NAME> set for every enabled feature
CARGO_MANIFEST_DIR, CARGO_PKG_VERSION as for normal crates

A first build script

bash · try it yourself
cargo new stamp --vcs none -q
cd stamp
cat > build.rs <<'RS'
use std::env;

fn main() {
    println!("cargo::rerun-if-changed=build.rs");
    println!("cargo::rustc-env=BUILT_FOR={}", env::var("TARGET").unwrap());
    println!("cargo::rustc-env=BUILT_PROFILE={}", env::var("PROFILE").unwrap());
    println!("cargo::rustc-check-cfg=cfg(fast_math)");
    if env::var("CARGO_CFG_TARGET_ARCH").unwrap() == "x86_64" {
        println!("cargo::rustc-cfg=fast_math");
    }
    println!("cargo::warning=build script ran for {}", env::var("CARGO_PKG_NAME").unwrap());
}
RS
cat > src/main.rs <<'RS'
fn main() {
    println!("built for {} ({})", env!("BUILT_FOR"), env!("BUILT_PROFILE"));
    if cfg!(fast_math) { println!("fast_math enabled"); }
}
RS
cargo run 2>&1
echo "--- again: nothing changed"
cargo run 2>&1
echo "--- edit main.rs: the crate recompiles, the script does not rerun"
echo '// comment' >> src/main.rs
cargo build -v 2>&1 | grep -E 'Running|Fresh|Dirty|Compiling' | sed -E 's/ \([0-9.]+s, .*//; s/(rustc --crate-name [a-z_]+).*/\1 .../'
   Compiling stamp v0.1.0 (/home/learner/stamp)
warning: stamp@0.1.0: build script ran for stamp
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.26s
     Running `target/debug/stamp`
built for x86_64-unknown-linux-gnu (debug)
fast_math enabled
--- again: nothing changed
warning: stamp@0.1.0: build script ran for stamp
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.00s
     Running `target/debug/stamp`
built for x86_64-unknown-linux-gnu (debug)
fast_math enabled
--- edit main.rs: the crate recompiles, the script does not rerun
       Dirty stamp v0.1.0 (/home/learner/stamp): the file `src/main.rs` has changed
   Compiling stamp v0.1.0 (/home/learner/stamp)
     Running `/opt/rustup/toolchains/1.99.1-x86_64-unknown-linux-gnu/bin/rustc --crate-name stamp ...
  • The cargo::warning is shown on the first build and replayed on later builds from the cache, so the user sees it every time.
  • Editing src/main.rs recompiled the crate (Running rustc), but the build script wasn't rerun: it declared that only build.rs matters.
  • -v shows Cargo's decisions (Fresh, Dirty … because …, Running), which is how you debug unexpected rebuilds.

Rerun rules and the classic mistake

  • No rerun-if directive at all: Cargo reruns the script whenever any file in the package changes. Safe, but slow for big packages.
  • At least one rerun-if-changed: only the listed paths count. List every input the script reads.
  • A path that doesn't exist counts as changed on every build:
bash · try it yourself
cargo new stamp --vcs none -q
cd stamp
cat > build.rs <<'RS'
fn main() {
    println!("cargo::rerun-if-changed=build.rs");
    println!("cargo::rerun-if-changed=config/feature-flags.txt");
}
RS
cargo build 2>&1
cargo build 2>&1
cargo build -v 2>&1 | grep Dirty
   Compiling stamp v0.1.0 (/home/learner/stamp)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.23s
   Compiling stamp v0.1.0 (/home/learner/stamp)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.08s
       Dirty stamp v0.1.0 (/home/learner/stamp): the file `config/feature-flags.txt` is missing

The script reruns forever, so the crate (and everything that depends on it) recompiles on every build. Typo'd paths in rerun-if-changed are a common cause of "why does my workspace always rebuild?".

MSRV and the cargo:: syntax

bash · try it yourself
cargo new stamp --vcs none -q
cd stamp
sed -i 's/^edition = .*/edition = "2021"\nrust-version = "1.70"/' Cargo.toml
echo 'fn main() { println!("cargo::rerun-if-changed=build.rs"); }' > build.rs
cargo build 2>&1
   Compiling stamp v0.1.0 (/home/learner/stamp)
error: the `cargo::` syntax for build script output instructions was added in Rust 1.77.0, but the minimum supported Rust version of `stamp v0.1.0 (/home/learner/stamp)` is 1.70.
Switch to the old `cargo:rerun-if-changed=build.rs` syntax (note the single colon).
See https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script for more information about build script outputs.

A crate that promises to build with Rust 1.70 can't use syntax Rust 1.70 doesn't understand, and Cargo enforces that.

Test yourself

Inside build.rs, how do you learn the architecture of the machine you're building FOR when cross-compiling?

  1. cfg!(target_arch = "aarch64")
  2. env::var("CARGO_CFG_TARGET_ARCH")
  3. std::env::consts::ARCH
  4. env::var("HOST")

A build script prints cargo::rerun-if-changed=data.csv, but the file is named Data.csv. What happens?

  1. Cargo finds it case-insensitively
  2. The script reruns on every build because the listed path doesn't exist
  3. The script never reruns
  4. The build fails

What is the difference between cargo::rustc-env=V=1 and cargo:rustc-env=V=1?

  1. None at all
  2. Same effect; cargo:: is the newer syntax (Rust 1.77+), cargo: the legacy one still accepted
  3. cargo: sets the variable at runtime
  4. cargo:: only works on nightly