skip to content

In a Cargo package, what is build.rs, when does Cargo run it, and how does it pass instructions back to Cargo?

level: juniorimportance: should knowfreq 30%

answer

  1. a program, not a config file
  2. compiled first, then run
  3. before the package's own crates
  4. stdout lines with a cargo:: prefix
  5. hidden unless -vv or a failure

basics

~20 s

build.rs is a Rust program in the package root that Cargo compiles and runs just before compiling the package. It talks to Cargo by printing cargo:: lines to stdout, and a panic or non-zero exit stops the build.

solid answer

~40 s

`build.rs` in the package root is a **build script**. Cargo compiles it into an executable, linking only its `[build-dependencies]` (never the package's `[dependencies]`), runs it, and only then compiles the package's own crates. The script starts in the package root and gets its inputs as environment variables such as `OUT_DIR`, `TARGET` and `PROFILE`. It answers on stdout: each line starting with `cargo::` is an instruction (`cargo::rustc-link-lib=...`, `cargo::rerun-if-changed=...`, `cargo::warning=...`), and every other line is ignored. Apart from `cargo::warning` messages, the output is hidden in a normal build; it is saved to `target/debug/build/<pkg>-<hash>/output`; `cargo build -vv` shows it live. A panic or non-zero exit fails the build and prints the script's output. The `cargo::` prefix needs Cargo 1.77; older code writes `cargo:`.

code

rust · 8 lines
rust
// build.rs in the tinyz package
fn main() {
    // An ordinary line: Cargo ignores it, but saves it in the output file.
    println!("generating CRC table");
    // Instructions: lines that start with cargo::
    println!("cargo::rerun-if-changed=build.rs");
    println!("cargo::warning=using the bundled C sources");
}

go deeper

for a junior

Recall that build.rs is a program Cargo compiles and runs before the package, and that it talks back through cargo:: lines on stdout.

for a middle

Explain the inputs (OUT_DIR, TARGET, CARGO_CFG_*), where the saved output lives, why [build-dependencies] are separate, and how -vv reveals what the script printed.

for a senior

Know the failure modes: a cargo:: typo is an error while a cargo: typo silently becomes metadata, and a rust-version below 1.77 forbids the new prefix.

for a principal

Treat a build script as code every user of the crate runs on their machine; keep it small, deterministic and offline-safe so builds stay reproducible.

## What a build script is A **build script** is an ordinary Rust program, conventionally `build.rs` in the package root, that Cargo runs as a step of building the package. It exists for the jobs a manifest cannot describe: compiling a bundled C library, finding a system library, generating Rust source from a specification, or probing the platform. Cargo detects `build.rs` automatically; the `build` key in `[package]` points at another file (`build = "tools/build.rs"`) or switches detection off (`build = false`). The script is a separate crate. It can use only the crates listed under `[build-dependencies]`, because the package's `[dependencies]` and `[dev-dependencies]` are not built yet when it runs, and it is compiled for the machine running Cargo (the **host**), not for the platform being built. ## The life cycle For a package with a build script, `cargo build` does this: 1. Compile `build.rs` and its build dependencies into an executable, unless an up-to-date one already exists. Cargo rebuilds it when the script's source or its dependencies change. 2. Run that executable with the package root as its current directory and a set of environment variables as its input. 3. Read what it printed to stdout and turn the `cargo::` lines into instructions. 4. If it exited successfully, compile the package's library, binaries and other targets with those instructions applied. On a later build Cargo decides from its change-detection rules whether to run the script again; if nothing it watches has changed, the saved output is reused without running the script. ## Inputs: environment variables Cargo passes everything the script needs to know through the environment, read at run time with `std::env::var`: - `OUT_DIR`: the directory where the script must put generated files. - `TARGET` and `HOST`: the triple being compiled for, and the compiler's own triple. - `PROFILE`, `OPT_LEVEL` and `DEBUG`: the build settings, with `OPT_LEVEL` and `DEBUG` the more precise of them. - `CARGO_CFG_*`: the target's configuration, such as `CARGO_CFG_TARGET_OS`. - `CARGO_FEATURE_<NAME>`: one variable per enabled Cargo feature. - `CARGO_MANIFEST_DIR`: the package root, also the starting directory. ## Outputs: the stdout protocol The script communicates by printing lines. Cargo treats each line that begins with `cargo::` as an instruction and ignores the rest, so progress messages are harmless. The common instructions are: | Instruction | Effect | |---|---| | `cargo::rerun-if-changed=PATH` | rerun the script when that file or directory changes | | `cargo::rerun-if-env-changed=VAR` | rerun it when that environment variable changes | | `cargo::rustc-link-lib=LIB` | link a native library (`-l`) | | `cargo::rustc-link-search=[KIND=]PATH` | add a library search path (`-L`) | | `cargo::rustc-cfg=KEY[="VALUE"]` | set a `--cfg` for the package's crates | | `cargo::rustc-env=VAR=VALUE` | set a variable that `env!` reads at compile time | | `cargo::warning=MESSAGE` | show a warning after the script finishes | | `cargo::error=MESSAGE` | show an error and fail the build (Cargo 1.84) | | `cargo::metadata=KEY=VALUE` | pass data to dependents' build scripts (needs `links`) | In a normal build the output stays hidden. Cargo writes stdout to `target/debug/build/<pkg>-<hash>/output` and stderr beside it, and `cargo build -vv` prints each line live, prefixed with the package name. Warnings from `cargo::warning` appear for local path packages; for crates from a registry they are shown only with `-vv` or when the build fails. ## cargo:: versus cargo: The two-colon prefix arrived in **Cargo 1.77**. Before it, instructions were written `cargo:KEY=VALUE`, and that form still works, which is why many published build scripts and helper crates print it. The two forms differ on mistakes: - With `cargo::`, an unknown key such as `cargo::rerun-if-chaned=build.rs` is an error: Cargo 1.99 stops with `invalid output in build script` and `Unknown key: \`rerun-if-chaned\``. - With `cargo:`, an unknown key is silently taken as metadata for dependents, so the typo does nothing. - If `rust-version` in the manifest is below 1.77, Cargo refuses `cargo::` lines and tells you to switch to the single-colon form. ## When the script fails A build script signals failure by panicking or exiting with a non-zero status. Cargo then stops the build with `failed to run custom build command for` the package and prints the script's captured stdout and stderr, so `unwrap` on a missing library already gives a readable report. Since Cargo 1.84 a script can also print `cargo::error=MESSAGE`, which displays the message and fails the build after the script finishes; a library meant to be called from other build scripts may do better returning a `Result` and letting its caller decide.

  • Where do you find what a build script printed when the build succeeded?
    Cargo saves stdout in `target/debug/build/<pkg>-<hash>/output` and stderr in a `stderr` file in the same directory (under `target/release/` for release builds). To watch it live, run `cargo build -vv`, which prints each line prefixed with the package name and version, but only when the script actually runs.
  • How do you point Cargo at a build script that is not called build.rs, or turn one off?
    Set the `build` key in `[package]`: `build = "tools/codegen.rs"` uses that file, and `build = false` disables automatic detection of `build.rs`. A package that declares a `links` key must still have a build script.
  • What is the difference between cargo::warning and cargo::error?
    `cargo::warning=MESSAGE` shows a warning after the script finishes and the build continues; it appears for local path packages, and for registry crates only with `-vv`. `cargo::error=MESSAGE`, added in Cargo 1.84, shows the message and then fails the build, without the script having to panic.

  • build.rs is a configuration file that Cargo reads instead of running.
  • A build script can use the crates listed under [dependencies].
  • Everything a build script prints appears in a normal cargo build.
  • Build scripts run after the crate compiles, to post-process the binary.
  • The single-colon cargo: prefix stopped working once cargo:: arrived.

Assumes Cargo 1.99; the cargo:: prefix needs Cargo 1.77 and cargo::error needs Cargo 1.84, while the older cargo: prefix still works.