How to Use Build Scripts (build.rs) in Cargo

Create a build.rs file in your project root to run custom code before compilation.

Create a build.rs file in your project root to run custom code before compilation. This script executes automatically when you run cargo build and can generate code, compile C libraries, or set environment variables.

// build.rs
use std::env;
use std::fs::File;
use std::io::Write;
use std::path::Path;

fn main() {
    let out_dir = env::var("OUT_DIR").unwrap();
    let dest_path = Path::new(&out_dir).join("generated.rs");
    let mut f = File::create(&dest_path).unwrap();
    writeln!(f, "pub const VERSION: &str = \"1.0\";").unwrap();
    println!("cargo:rerun-if-changed=build.rs");
}

In your src/main.rs, include the generated file:

include!(concat!(env!("OUT_DIR"), "/generated.rs"));

fn main() {
    println!("Version: {}", VERSION);
}