I want to set rustc-env=VAR=VALUE so that I could access it using env::var("VAR") in my code. However, I'm not clear on where to specify it. Can I set the environment variable VAR in the Makefile?
build.rs
fn main() {
println!("cargo:rustc-env=VAR=VALUE");
}
src/main.rs
fn main() {
let var = env!("VAR");
}
The documentation that you linked is for a Cargo build script:
The Rust file designated by the
buildcommand (relative to the package root) will be compiled and invoked before anything else is compiled in the package, allowing your Rust code to depend on the built or generated artifacts. By default Cargo looks up for"build.rs"file in a package root (even if you do not specify a value forbuild). Usebuild = "custom_build_name.rs"to specify a custom build name orbuild = falseto disable automatic detection of the build script.
On the same page, there's a section that describes outputs of build.rs
All the lines printed to stdout by a build script are written to a file [...] Any line that starts with
cargo:is interpreted directly by Cargo. This line must be of the formcargo:key=value, like the examples below:cargo:rustc-env=FOO=bar
It then details rustc-env:
rustc-env=VAR=VALUEindicates that the specified environment variable will be added to the environment which the compiler is run within. The value can be then retrieved by theenv!macro in the compiled crate. This is useful for embedding additional metadata in crate's code, such as the hash of Git HEAD or the unique identifier of a continuous integration server.
env! is a macro.
access it using
env::var("VAR")
No. env::var is for reading environment variables set when the program runs, not when the program is compiled.
See also:
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