51

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"); } 
7
  • Possible duplicate of How to specify an environment variable using the rustc-env flag? Commented Jul 13, 2019 at 7:40
  • 8
    It is correct English. It's not a duplicate. I'm trying to set a compile time environment variable. The link speaks of a runtime environment variable. Commented Jul 13, 2019 at 7:54
  • 2
    I'm not sure it's possible, see github.com/rust-lang/cargo/issues/4121. Commented Jul 13, 2019 at 8:07
  • 1
    What is the dependency in question? How does it use the environment variable? Commented Jul 13, 2019 at 16:35
  • 1
    @Stargateur it is correct English (source: a lifetime of being English). "but" here not meaning "except", but rather acting as a conjunction for the rest of the following clause. Commented Oct 11, 2019 at 10:24

1 Answer 1

68
+100

Since Cargo 1.56, you can use the 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.

Sign up to request clarification or add additional context in comments.

12 Comments

Awesome! Anything that can be used in the meantime?
I don't think so, the issue on cargo's repo asking for this feature was closed by the PR implementing this and I haven't seen any alternative. I guess you could use a bash script in the meantime.
Added a link at the end
Theses are environment variables set for the processes executed by cargo, not for use in the final binary! This is useful for building C dependencies for example. See stackoverflow.com/questions/51621642/… to check how to achieve what you want.
Is it possible to set different env vars if --release is set?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.