expression
Cargo build script for a static C library
A build script runs on the host before the crate is built. Here it compiles a reviewed C file and archives its object in OUT_DIR, then tells Cargo where to find the library. It declares C source and header inputs; toolchain changes require a clean rebuild. This example requires the accompanying Cargo project, trusted cc/ar on PATH, and a matching Linux target. Build scripts execute code at compile time: do not run this in the normal learner evaluator. Expected output of the final binary: 23 23 (not executed).
Formal Syntax & Structure
rust syntaxrust
cargo::rustc-link-search=native=PATH; cargo::rustc-link-lib=static=NAMEWorking Example
Example Snippetrust
use std::{env, path::PathBuf, process::Command};fn run(cmd: &mut Command) { assert!(cmd.status().expect("start reviewed tool").success(), "native tool failed");}fn main() { let host = env::var("HOST").unwrap(); let target = env::var("TARGET").unwrap(); assert_eq!(host, "x86_64-unknown-linux-gnu"); assert_eq!(target, host, "cross-compilation not supported by this fixture"); let out = PathBuf::from(env::var_os("OUT_DIR").unwrap()); let object = out.join("counter.o"); let archive = out.join("libbm105_counter.a"); run(Command::new("cc").args(["-std=c11", "-Wall", "-Wextra", "-Werror", "-c", "counter.c", "-o"]).arg(&object)); run(Command::new("ar").arg("crs").arg(&archive).arg(&object)); println!("cargo::rerun-if-changed=counter.c"); println!("cargo::rerun-if-changed=counter.h"); println!("cargo::rustc-link-search=native={}", out.display()); println!("cargo::rustc-link-lib=static=bm105_counter");}