A Cargo build script is an optional Rust program named build.rs in the project root. Cargo compiles and runs it before building the application, enabling build-time tasks that static configuration cannot handle. section 3.2.2
Use a build script when a project needs custom build steps:
- Generate a linker script such as memory.x, write it to OUT_DIR, and add that directory to the linker search path. section 3.2.2
- Compile C source files with the cc crate and link the resulting library during a normal Cargo build. section 8.2.6
- Coordinate assembling and linking external .S files. For a prebuilt C library, direct linking may be enough, with a build script or Cargo configuration supplying its directory if needed. section 5.5.5 section 8.2.6
- Skip build.rs for simple projects that need no custom build steps or complex native-code integration. section 3.2.2
use std::{env, fs::File, io::Write, path::PathBuf};
fn main() {
let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
let mut file = File::create(out_dir.join("memory.x")).unwrap();
writeln!(
file,
"MEMORY\n{{\n FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 64K\n
RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 20K\n}}"
)
.unwrap();
println!("cargo:rustc-link-search={}", out_dir.display());
}
This listing shows a build script creating memory.x inside OUT_DIR and emitting a linker search-path directive. section 3.2.2


