In Cargo, when does a package's build script rerun, and how do cargo::rerun-if-changed and cargo::rerun-if-env-changed change that rule?
answer
- conservative by default
- any package file changes
- one rerun-if line replaces the scan
- mtime of the listed path
- variables Cargo received, not set
basics
~20 sWith no rerun-if lines, Cargo reruns a build script whenever any file in the package changes. Once the script prints one, Cargo stops that scan and watches what was listed: a path's modification time, or an environment variable's value.
solid answer
~40 sCargo's default is conservative: if the script prints no `rerun-if` instruction, any change to a file in the package (even `README.md`) reruns it. As soon as it prints `cargo::rerun-if-changed=PATH` or `cargo::rerun-if-env-changed=VAR`, Cargo watches the listed inputs instead of the package. `rerun-if-changed` compares the path's modification time with the time of the script's last run, and a directory is scanned recursively; `cargo::rerun-if-changed=build.rs` therefore means "rerun only after the script is edited", because Cargo recompiles and reruns a changed script anyway. `rerun-if-env-changed` tracks variables Cargo itself received, such as `CC` or `TINYZ_DIR`, not ones Cargo sets for the script, like `TARGET`. A listed path that does not exist reruns the script on every build, and `cargo build -v` names the reason on its `Dirty` line.
code
rust · 12 lines// build.rs
fn main() {
// Inputs the script reads: list every one, because the first
// rerun-if line turns off Cargo's whole-package scan.
println!("cargo::rerun-if-changed=build.rs");
println!("cargo::rerun-if-changed=csrc"); // a directory: scanned recursively
println!("cargo::rerun-if-env-changed=TINYZ_DIR");
if let Ok(dir) = std::env::var("TINYZ_DIR") {
println!("cargo::warning=using libtinyz from {dir}");
}
}go deeper
Recall that a build script with no rerun-if lines reruns whenever any package file changes, and that rerun-if lines narrow that.
Explain that the first rerun-if line replaces the scan, that rerun-if-changed uses mtimes and directories, and which variables rerun-if-env-changed can watch.
Diagnose reruns with cargo build -v and its Dirty reason: a missing listed file, an incomplete list, or a helper crate's rerun lines switching the scan off.
Set a team rule that every build script declares its complete inputs, so incremental builds stay fast and correct across CI and laptops.
## Why change detection matters Cargo builds incrementally: a second `cargo build` with no edits should do almost nothing. A **build script** complicates that, because Cargo cannot see what the script reads. It might compile C files, read a data file, or probe an environment variable. Cargo must decide on every build whether the saved output of the last run is still valid or whether the script has to run again, and a script that reruns needlessly can force the package to recompile each time. ## The default rule If a script prints no `rerun-if` instruction, Cargo takes the safe route: it reruns the script whenever **any file in the package** changes (the package's file list, which `include` and `exclude` in the manifest control). Editing `src/lib.rs` or touching `README.md` is enough. That is correct but wasteful, so the Cargo reference recommends that every build script print at least one `rerun-if` instruction. ## The two instructions | Instruction | Reruns the script when | |---|---| | no `rerun-if` line at all | any file in the package changes | | `cargo::rerun-if-changed=PATH` (a file) | that file's modification time differs from the script's last run | | `cargo::rerun-if-changed=PATH` (a directory) | anything inside the directory changes | | `cargo::rerun-if-changed=build.rs` | only when the script is edited, which recompiles it anyway | | `cargo::rerun-if-env-changed=VAR` | the value Cargo received for `VAR` changes | The key rule is that **printing any rerun-if line replaces the default scan**. From then on Cargo watches the listed paths and variables instead of the whole package, so the list must be complete. Details worth knowing about `rerun-if-changed`: - Cargo currently compares **modification times** (mtime), not file contents, against a cached timestamp of the script's last run. - Relative paths are taken from the package root, which is also the script's working directory. - Cargo already reruns a script after recompiling it, so listing `build.rs` matters only as a way to say "watch nothing else". Details worth knowing about `rerun-if-env-changed`: - It names variables in the environment **Cargo was started with**, like `CC`, `CFLAGS` or a crate's own `TINYZ_DIR`. - It cannot watch variables Cargo sets for build scripts, such as `TARGET` or `OUT_DIR`. - Variables the crate's code reads through `env!` or `option_env!` are tracked automatically, so they need no instruction. ## Choosing what to list A complete list names exactly what the script reads, and nothing it writes: - every **input file**: a data file a table is generated from, each C source and header, a schema or IDL file; - a **directory** when its contents change as a set, keeping in mind that anything dropped into it reruns the script; - every **environment variable** the script consults with `std::env::var`, such as `TINYZ_DIR` or a `TINYZ_STATIC` switch; - never its own outputs in `OUT_DIR`, and never a broad directory such as `src/` that the crate edits constantly, which would bring back the cost the list was meant to remove. When the script reads nothing at all, `cargo::rerun-if-changed=build.rs` is the conventional way to say so. ## Two traps 1. **A path that never exists.** If the script prints `cargo::rerun-if-changed=data/crc.txt` and nothing creates that file, Cargo treats it as missing on every build and reruns the script each time, assuming the script will produce it. The fix is to stop printing the line, or to point it at a file that exists. 2. **An incomplete list.** Because one `rerun-if` line switches the scan off, a script that lists one input but reads three will miss edits to the other two. This bites hardest when a helper crate prints `rerun-if` lines on the script's behalf: the C-compiler helper `cc` prints `rerun-if-env-changed` lines for variables such as `CC` and `CFLAGS`, so a script using it must still list its C sources itself. ## Diagnosing an unexpected rerun Run `cargo build -v`. When a package is rebuilt, Cargo prints a `Dirty` line with the reason, for example ``the file `data/crc.txt` is missing``, ``the file `csrc/tinyz.c` has changed`` or `the env variable CFLAGS changed`, followed by the `Running` line for the script. For deeper digging, the Cargo FAQ suggests `CARGO_LOG=cargo::compiler::fingerprint=info cargo build`, which logs the fingerprint comparisons Cargo makes. Other rebuild causes, such as two commands enabling different features of a dependency, show up there too.
- Why does adding cargo::rerun-if-changed=build.rs stop the script rerunning after an edit to src/lib.rs, yet the crate still recompiles?The script and the crate are tracked separately. With a `rerun-if` line, the script's own fingerprint covers only `build.rs`, so editing `src/lib.rs` leaves its saved output valid. The library's fingerprint still covers its sources, so rustc recompiles the crate with the old instructions.
- A crate reads an API key with env!("TINYZ_KEY") in its code. Does the build script need cargo::rerun-if-env-changed=TINYZ_KEY?No. Cargo tracks variables read by `env!` and `option_env!` in the crate's source and rebuilds when they change. `rerun-if-env-changed` is for variables the build script reads at run time with `std::env::var`.
- Why can a Cargo build script rerun after switching git branches and back, although no listed file's content changed?`rerun-if-changed` compares modification times, not contents. If a listed file differs between two branches, switching away and back rewrites it with the original bytes but a new mtime, and a formatter or code generator that rewrites a file unchanged does the same, so Cargo sees a newer timestamp than the script's last run and reruns it.
A build script's rerun list works like a house-sitter's checklist: with no checklist they walk through every room on each visit, but once you hand them a list they check only the rooms on it, so a room you forgot to write down goes unchecked.
- Printing one rerun-if-changed line adds to the default package scan.
- cargo::rerun-if-env-changed=TARGET reruns the script when the target changes.
- Cargo compares the content hash of each listed file to decide on a rerun.
- A build script with no rerun-if lines runs only once per clean build.
- Listing a path that does not exist is harmless; Cargo just ignores it.