A build.rs file at the crate root is compiled and run before the crate itself. Essential for embedded projects.

Common uses:

Link linker scripts:

// build.rs
fn main() {
    println!("cargo:rustc-link-arg=-Tmemory.x");
    println!("cargo:rustc-link-arg=-Tlink.x");
}

Generate register maps from SVD files:

// Generate PAC from vendor SVD
svd2rust --input stm32f407.svd --output src/

Conditional compilation based on environment:

if std::env::var("CARGO_CFG_TARGET_ARCH").unwrap() == "riscv32" {
    println!("cargo:rustc-cfg=risc_v_target");
}

Embed version information:

let version = env!("CARGO_PKG_VERSION");
println!("cargo:rustc-env=FIRMWARE_VERSION={}", version);
// Access in firmware: env!("FIRMWARE_VERSION")

In SpaceCAN, the build script validates that the target triple is a known supported MCU and emits an error with a helpful message if an unsupported target is selected.