I want to set an environment variable before building my project, or mostly, before running the tests or executable. I tried using std::process:Command
to run sh -c "source ./my_setup_script.sh"
, but that did not effect the current environment.
Because I only have one variable to set, I then tried std::env::set_env
, but this also did not affect my current environment (where I call cargo test
from). Why is that?
What do you expect to read that variable?
For example, your build.rs
is run after all your dependencies have finished building, so there's absolutely no way to send an env variable back in time to affect your dependencies.
I need the environment variable in my executable program to read a private key file. The environment variable should contain the path to the file.
To communicate with your program you can create a file in OUT_DIR
and have your code include it
const key: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/keyfile")));
As for env vars, you're just modifying your build script's environment, not the environment that the program runs in. Env variables aren't global, they're per process and inherited down to subprocesses, but not up.
That would work in my case, as I can control how the key file is read. But I am still wondering how I would do this if I was using an external library which specifically requires an environment variable to be set. Is there any way to "export" environment variables from a rust process?
https://doc.rust-lang.org/cargo/reference/build-scripts.html#outputs-of-the-build-script
For the build script, print
cargo:rustc-env=FOO=bar
to tell cargo/rustc to set environment value FOO
to bar
during compilation.
There isn't any way to set an env var for tests programmatically that I know of other than the super fragile and doesn't work most of the time "#[test] fn __________this_probably_runs_first() { env::set_env("FOO", "bar"); }
.
You could consider using an xtask
wrapper and/or cargo alias to wrap the rest with some setup.
Thanks a lot, println!("cargo:rustc-env=FOO=bar")
in build.rs seems to work fine! I should have read the reference more carefully.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.