Conditionnal build based on an environment variable

I want to have some section of my Rust code to be compiled based on an environment variable provided at build time. But for now without success. The cargo command don't seems to get my environment variable.

Here what I have:

The conditionnal code :

#[cfg(compile_env = "prod")] {
        // Some Rust code here
}

The build.rs file :

// build.rs
use std;

fn main() {

    let env = std::env::var("COMPILE_ENV").unwrap_or("prod".to_string());
    println!("cargo:rustc-cfg=compile_env=\"{}\"", env);
}

and tying to build the programm with the supplyied env variable :

COMPILE_ENV=dev cargo build

If I do like this it always takes the default value for the environement as if it don't see the environment variable.
If I hard code the value of the variable "env" to "dev" I can validate that conditionnal compiling is working well.
The problem seems to be about providing the environment variable to cargo.

How to do that?

1 Like

did you try:

println!("cargo:rerun-if-env-changed=COMPILE_ENV");
3 Likes

Wonderfull! It now takes in account the env variable!
The final code :

// build.rs
use std;

fn main() {

    let env = std::env::var("COMPILE_ENV").unwrap_or("prod".to_string());
    println!("cargo:rerun-if-env-changed=COMPILE_ENV");
    println!("cargo:rustc-cfg=compile_env=\"{}\"", env);
}

Thansk a lot

By the way, this is unnecessary. As a general rule, you never need to write a use with one path component (use foo as opposed to use foo::bar), except in certain unusual situations where you are setting up re-exports.

use std can only succeed if std is already in scope, so it has no effect relevant to using std in the same module.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.