Usage of cargo:rustc-env=FOO=bar


#1

Hi,
What is the use case for cargo:rustc-env=FOO=bar in a build script?
According to the documentation https://doc.rust-lang.org/cargo/reference/build-scripts.html, it “indicates that the specified environment variable will be added to the environment which the compiler is run within and the value can be then retrieved by the env! macro in the compiled crate”.
I’m not sure how exactly to use this. Can someone give me an example? Would really appreciate it


#2

build.rs

fn main() {
    println!("cargo:rustc-env=MEANING_OF_LIFE=42");
}

main.rs

fn main() {
    if env!("MEANING_OF_LIFE", "Earth Destroyed!") != "42" {
        panic!();
    }
    println!("Mostly Harmless");
}

#3

For example, embedding the output of git rev-parse HEAD so that the program can include the commit hash in --version output.