Environment Variables - The Cargo Book (original) (raw)

The Cargo Book

Environment Variables

Cargo sets and reads a number of environment variables which your code can detect or override. Here is a list of the variables Cargo sets, organized by when it interacts with them:

Environment variables Cargo reads

You can override these environment variables to change Cargo’s behavior on your system:

Configuration environment variables

Cargo reads environment variables for some configuration values. See the configuration chapter for more details. In summary, the supported environment variables are:

Environment variables Cargo sets for crates

Cargo exposes these environment variables to your crate when it is compiled. Note that this applies for running binaries with cargo run and cargo testas well. To get the value of any of these variables in a Rust program, do this:

let version = env!("CARGO_PKG_VERSION");

version will now contain the value of CARGO_PKG_VERSION.

Note that if one of these values is not provided in the manifest, the corresponding environment variable is set to the empty string, "".

Dynamic library paths

Cargo also sets the dynamic library path when compiling and running binaries with commands like cargo run and cargo test. This helps with locating shared libraries that are part of the build process. The variable name depends on the platform:

The value is extended from the existing value when Cargo starts. macOS has special consideration where if DYLD_FALLBACK_LIBRARY_PATH is not already set, it will add the default $HOME/lib:/usr/local/lib:/usr/lib.

Cargo includes the following paths:

Environment variables Cargo sets for build scripts

Cargo sets several environment variables when build scripts are run. Because these variables are not yet set when the build script is compiled, the above example using env! won’t work and instead you’ll need to retrieve the values when the build script is run:

use std::env;
let out_dir = env::var("OUT_DIR").unwrap();

out_dir will now contain the value of OUT_DIR.

Environment variables Cargo sets for 3rd party subcommands

Cargo exposes this environment variable to 3rd party subcommands (ie. programs named cargo-foobar placed in $PATH):

For extended information about your environment you may run cargo metadata.