TExcelTAD
Home › Cargo in Depth › Generated Code in OUT_DIR

Generated Code in OUT_DIR

Some Rust code is better written by a program: lookup tables, bindings to a C header, types generated from a .proto schema, version information from Git. A build script can generate that code at build time, write it into OUT_DIR, and the crate pulls it in with include!.

The pattern

rust
// build.rs
let out = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).join("units.rs");
std::fs::write(&out, generated_source).unwrap();

// src/lib.rs (or main.rs)
include!(concat!(env!("OUT_DIR"), "/units.rs"));

Three rules:

  • Write only to OUT_DIR. Never into src/: the source folder may be read-only (a vendored or registry crate is), and writing there triggers rebuild loops.
  • Declare every input with rerun-if-changed, so the code is regenerated exactly when the data changes.
  • Keep the output deterministic (sorted, no timestamps), or every build changes the file and invalidates caches.

A table generated from a data file

A unit-conversion crate keeps its conversion factors in a CSV file that non-programmers edit. The build script turns it into a match:

bash · try it yourself
cargo new units --vcs none -q
cd units
cat > units.csv <<'CSV'
unit,metres
km,1000
mile,1609.344
ft,0.3048
inch,0.0254
CSV
cat > build.rs <<'RS'
use std::{env, fs, path::Path};

fn main() {
    println!("cargo::rerun-if-changed=units.csv");
    let csv = fs::read_to_string("units.csv").unwrap();
    let mut rows: Vec<(String, String)> = csv.lines().skip(1)
        .filter(|l| !l.trim().is_empty())
        .map(|l| { let (u, m) = l.split_once(',').unwrap(); (u.trim().to_string(), m.trim().to_string()) })
        .collect();
    rows.sort();                                   // deterministic output
    let mut code = String::from("/// Generated from units.csv by build.rs. Do not edit.\n");
    code += &format!("pub const UNITS: [&str; {}] = [{}];\n", rows.len(),
        rows.iter().map(|(u, _)| format!("{u:?}")).collect::<Vec<_>>().join(", "));
    code += "pub fn to_metres(unit: &str) -> Option<f64> {\n    match unit {\n";
    for (u, m) in &rows { code += &format!("        {u:?} => Some({m}_f64),\n"); }
    code += "        _ => None,\n    }\n}\n";
    fs::write(Path::new(&env::var("OUT_DIR").unwrap()).join("units.rs"), code).unwrap();
}
RS
cat > src/main.rs <<'RS'
include!(concat!(env!("OUT_DIR"), "/units.rs"));

fn main() {
    println!("known units: {}", UNITS.join(", "));
    println!("26.2 mile = {:.1} m", 26.2 * to_metres("mile").unwrap());
    println!("parsec: {:?}", to_metres("parsec"));
}
RS
cargo run -q
echo "--- the generated file"
cat target/debug/build/units-*/out/units.rs
echo "--- add a row: the script reruns"
echo 'yard,0.9144' >> units.csv
cargo run -q
known units: ft, inch, km, mile
26.2 mile = 42164.8 m
parsec: None
--- the generated file
/// Generated from units.csv by build.rs. Do not edit.
pub const UNITS: [&str; 4] = ["ft", "inch", "km", "mile"];
pub fn to_metres(unit: &str) -> Option<f64> {
    match unit {
        "ft" => Some(0.3048_f64),
        "inch" => Some(0.0254_f64),
        "km" => Some(1000_f64),
        "mile" => Some(1609.344_f64),
        _ => None,
    }
}
--- add a row: the script reruns
known units: ft, inch, km, mile, yard
26.2 mile = 42164.8 m
parsec: None

The generated match is ordinary Rust: the compiler type-checks and optimises it, and a typo in the CSV (a factor like 1,5) becomes a compile error pointing at the generated file.

Embedding version information from Git

Release builds often embed the commit they were built from. The build script asks git and passes the answer through rustc-env. Note the rerun conditions: the script must rerun when HEAD moves, but not on every source edit.

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

fn main() {
    println!("cargo::rerun-if-changed=.git/HEAD");
    println!("cargo::rerun-if-changed=.git/refs");
    let rev = Command::new("git").args(["describe", "--always", "--dirty"]).output()
        .ok().filter(|o| o.status.success())
        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
        .unwrap_or_else(|| "unknown".into());     // building from a .crate: no .git
    println!("cargo::rustc-env=GIT_REV={rev}");
}
RS
echo 'fn main() { println!("tool {} ({})", env!("CARGO_PKG_VERSION"), env!("GIT_REV")); }' > src/main.rs
echo "--- no repository yet"
cargo run -q
echo "--- first commit"
echo 'target' > .gitignore
git init -q && git add . && git commit -qm "first version"
cargo run -q
echo "--- tagged release"
git tag -a v0.1.0 -m "release 0.1.0"
cargo run -q
echo "--- one commit after the tag, plus an uncommitted edit"
echo '# Tool' > README.md && git add README.md && git commit -qm "add readme"
echo 'more' >> README.md
cargo run -q
--- no repository yet
tool 0.1.0 (unknown)
--- first commit
tool 0.1.0 (c73e0e1)
--- tagged release
tool 0.1.0 (v0.1.0)
--- one commit after the tag, plus an uncommitted edit
tool 0.1.0 (v0.1.0-1-gfde0497-dirty)

git describe gives exactly the string a release needs: a bare commit hash, then the tag name on the tagged commit, then v0.1.0-1-g<hash>-dirty (one commit after the tag, with uncommitted changes). Before git init there was no repository, and the script fell back to unknown instead of failing: crates downloaded from a registry have no .git, so a build script must never require it. (The commit hashes are stable here because the recording machine fixes the Git author dates.) One trade-off is deliberate: an uncommitted edit on its own doesn't rerun the script, because it only watches .git/HEAD and .git/refs; here the new commit triggered the rerun, and git describe then noticed the dirty file. Watching the whole working tree would rerun the script on every edit.

Other generators you'll meet

Tool Generates Typically from
bindgen Rust declarations for a C/C++ header build.rs of a -sys crate, or ahead of time
cbindgen a C header for your Rust library build.rs or a release step
prost-build, tonic-build Protobuf/gRPC types build.rs, .proto files
proc macros (serde_derive, clap_derive) code from Rust syntax compiler, no build.rs
cargo xtask / checked-in code anything a manual or CI step; output committed to Git

Checked-in generated code (regenerated by a command and verified in CI) is often the better choice for big generators like bindgen: users don't need the generator's dependencies (libclang) and builds are faster.

Test yourself

Where may a build script write generated source files?

  1. src/generated/
  2. OUT_DIR
  3. The workspace root
  4. Anywhere under target/

How does the crate use a file generated into OUT_DIR?

  1. mod generated;
  2. include!(concat!(env!("OUT_DIR"), "/units.rs"));
  3. use OUT_DIR::units;
  4. Cargo adds it automatically

Why did the git-describe build script fall back to "unknown" instead of panicking?

  1. git is not allowed in build scripts
  2. A crate built from a registry or vendored copy has no .git directory; the build must still succeed
  3. To make builds faster
  4. Cargo forbids panics in build.rs