Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify an environment variable using the rustc-env flag?

Tags:

rust

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?

like image 323
Dragonight Avatar asked Jul 31 '18 20:07

Dragonight


1 Answers

TL;DR

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 build command (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 for build). Use build = "custom_build_name.rs" to specify a custom build name or build = false to 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 form cargo:key=value, like the examples below:

cargo:rustc-env=FOO=bar

It then details rustc-env:

rustc-env=VAR=VALUE indicates that the specified environment variable will be added to the environment which the compiler is run within. The value can be then retrieved by the env! 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:

  • Is it possible to initialize a variable from an environment variable at compilation time when using no_std?
like image 117
Shepmaster Avatar answered Oct 27 '22 17:10

Shepmaster