Should env! cause rebuild is env var changes


Sorry if this has been discussed before, I couldn’t find anything in the search or in Rustlang issues.

Should the env! macro cause a rebuild if the value of the env var changes?

I tried this simple example:

fn main() {
println!(“Hello, world! {:?}”, env!(“BUILD_NUMBER”));

BUILD_NUMBER=1 cargo build
BUILD_NUMBER=2 cargo build

Produces a binary the writes
Hello, world! "1"

So it’s not rebuilt with the new env var value.

(Tried using a recent nightly and latest stable)




Though env! is computed at compile time, if you don’t modify any of the text of the file, then Cargo will not even kick off a compile, so I wouldn’t expect it to, no.

There’s rerun-if-changed-env but beware of side effects:

1 Like

We use env vars and rerun-if-changed quite extensively throughout our build, sounds like we need to have a good look at what is actually built when these change, as we’ve made some invalid assumptions.

Thanks for your help @steveklabnikand @kornel.

For anyone else who runs into this issue, this is how we solved it in the end:

Adding a

use std::fs;
use std::io::Write;
use std::path::Path;

pub fn main() {

    let mut fout = fs::File::create(Path::new("./src/")).unwrap();

        "pub const BUILD_NUMBER: &'static str = \"{}\";",

Then adding mod build_number; to the and referencing the const string.