Question

How do I set environment variables with Cargo?

I have a dependency listed in Cargo.toml that needs a specific environment variable set. I can run export FOO=bar in bash and all works well, but for the life of me I can't figure out how to export this environment variable at compile time with Cargo. I've tried setting the environment variable in build.rs via std::env, Command, and println!, all to no effect:

// build.rs
fn main() {
    Command::new("ls")
        .env("FOO", "bar")
        .spawn()
        .expect("ls command failed to start");
}
// build.rs
fn main() {
    std::env::set_var("FOO", "bar");
}
// build.rs
fn main() {
    println!("cargo:rustc-env=FOO=bar");
}
 46  55828  46
1 Jan 1970

Solution

 57

Since Cargo 1.56, you can use the configurable-env feature via the [env] section in config.toml. This is not the same file as Cargo.toml, but it can still be set per project:

[env]
FOO = "bar"
PATH_TO_SOME_TOOL = { value = "bin/tool", relative = true }
USERNAME = { value = "test_user", force = true }

Environment variables set in this section will be applied to the environment of any processes executed by Cargo.

relative means the variable represents a path relative to the location of the directory that contains the .cargo/ directory that contains the config.toml file.

force means the variable can override an existing environment variable.

For more information about the history of this feature, see the related GitHub issue.

2021-03-06