liveBook · Manning

Build script

As explained in Embedded Software with Rust

A Cargo build script is a Rust program, conventionally named build.rs, that Cargo runs before compiling a package to perform build-time tasks.

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

How Embedded Software with Rust covers it

How deep it goes
Explains automatic execution and demonstrates file generation and C compilation, while deferring advanced Rust-C and assembly workflows.
Examples
Demonstrates generating memory.x, compiling C source with cc, and incorporating separate .S files.
What you can do after
Apply it via Cargo to generate linker inputs or compile C sources as part of a normal build.
How it connects
Connects Cargo build scripts to linker scripts, OUT_DIR, linker search paths, C integration, and external assembly.

Also explained in

Compare how 3 books explain build script →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Embedded Software with Rust. The section links point to the parts of the book it draws on.