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"); }
Windows Environment Variables Do so by pressing the Windows and R key on your keyboard at the same time. Type sysdm. cpl into the input field and hit Enter or press Ok. In the new window that opens, click on the Advanced tab and afterwards on the Environment Variables button in the bottom right of the window.
Set an environment variable in Rust You can set an environment variable (for the scope of the currently running process) using the standard library too. To do so, we use env::set_var(key, value) .
To set an environment variable, use the command " export varname=value ", which sets the variable and exports it to the global environment (available to other processes). Enclosed the value with double quotes if it contains spaces. To set a local variable, use the command " varname =value " (or " set varname =value ").
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With