Purpose and mechanism of a Rust build.rs script
Cargo's build pipeline.
build.rs compiles and runs before the crate, emitting cargo: directives via stdout to set link flags, env vars, and rerun triggers; used to compile C, generate code, or probe the system.
WHAT THIS TESTS Whether you understand Cargo's extensibility point for build-time logic, how it communicates with the compiler, and when native linking or code generation requires it.
A GOOD ANSWER COVERS A build.rs at the crate root is a separate Rust program. Before compiling the crate, Cargo compiles build.rs for the host and runs it, capturing its stdout. The script influences the build by printing directives, for example cargo:rustc-link-lib=foo to link a library, cargo:rustc-link-search=native=/path to add a search directory, cargo:rerun-if-changed=path to scope rebuilds, cargo:rustc-cfg=feature to enable conditional compilation, and cargo:rustc-env to inject environment values readable via env! at compile time. Outputs are placed in OUT_DIR, which the crate can include! to pull in generated source. Common jobs are compiling bundled C or assembly with the cc crate, generating FFI bindings with bindgen, probing the system with pkg-config or vcpkg, and embedding build metadata such as a git hash.
COMMON WRONG ANSWERS Saying build.rs runs when the final binary executes; it runs at build time only. Believing it edits your committed source; it writes to OUT_DIR. Forgetting rerun-if-changed, which causes stale or excessive rebuilds.
LIKELY FOLLOW-UPS How do you avoid rebuilding every time? How do build-dependencies differ from normal dependencies? How does cross-compilation affect the host versus target distinction? How do you statically versus dynamically link the native library?
ONE CONCRETE EXAMPLE Linking against a vendored C compression library: build.rs uses cc::Build to compile the .c sources into a static archive in OUT_DIR, then prints cargo:rustc-link-lib=static=zfast and cargo:rustc-link-search=native plus the OUT_DIR path. The Rust crate declares the C functions in an extern block, and Cargo links the archive into the final binary, all driven by the script.
Read the original → doc.rust-lang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.