環境變數
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:
Cargo 讀取的環境變數
You can override these environment variables to change Cargo’s behavior on your system:
CARGO_LOG— Cargo uses thetracingcrate to display debug log messages. TheCARGO_LOGenvironment variable can be set to enable debug logging, with a value such astrace,debug, orwarn. Usually it is only used during debugging. For more details refer to the Debug logging.CARGO_HOME— Cargo maintains a local cache of the registry index and of git checkouts of crates. By default these are stored under$HOME/.cargo(%USERPROFILE%\.cargoon Windows), but this variable overrides the location of this directory. Once a crate is cached it is not removed by the clean command. For more details refer to the guide.CARGO_TARGET_DIR— Location of where to place all generated artifacts, relative to the current working directory. Seebuild.target-dirto set via config.CARGO— If set, Cargo will forward this value instead of setting it to its own auto-detected path when it builds crates and when it executes build scripts and external subcommands. This value is not directly executed by Cargo, and should always point at a command that behaves exactly likecargo, as that’s what users of the variable will be expecting.RUSTC— Instead of runningrustc, Cargo will execute this specified compiler instead. Seebuild.rustcto set via config.RUSTC_WRAPPER— Instead of simply runningrustc, Cargo will execute this specified wrapper, passing as its command-line arguments the rustc invocation, with the first argument being the path to the actual rustc. Useful to set up a build cache tool such assccache. Seebuild.rustc-wrapperto set via config. Setting this to the empty string overwrites the config and resets cargo to not use a wrapper.RUSTC_WORKSPACE_WRAPPER— Instead of simply runningrustc, for workspace members Cargo will execute this specified wrapper, passing as its command-line arguments the rustc invocation, with the first argument being the path to the actual rustc. When building a single-package project without workspaces, that package is considered to be the workspace. It affects the filename hash so that artifacts produced by the wrapper are cached separately. Seebuild.rustc-workspace-wrapperto set via config. Setting this to the empty string overwrites the config and resets cargo to not use a wrapper for workspace members. If bothRUSTC_WRAPPERandRUSTC_WORKSPACE_WRAPPERare set, then they will be nested: the final invocation is$RUSTC_WRAPPER $RUSTC_WORKSPACE_WRAPPER $RUSTC.RUSTDOC— Instead of runningrustdoc, Cargo will execute this specifiedrustdocinstance instead. Seebuild.rustdocto set via config.RUSTDOCFLAGS— A space-separated list of custom flags to pass to allrustdocinvocations that Cargo performs. In contrast withcargo rustdoc, this is useful for passing a flag to allrustdocinstances. Seebuild.rustdocflagsfor some more ways to set flags. This string is split by whitespace; for a more robust encoding of multiple arguments, seeCARGO_ENCODED_RUSTDOCFLAGS.CARGO_ENCODED_RUSTDOCFLAGS— A list of custom flags separated by0x1f(ASCII Unit Separator) to pass to allrustdocinvocations that Cargo performs.RUSTFLAGS— A space-separated list of custom flags to pass to all compiler invocations that Cargo performs. In contrast withcargo rustc, this is useful for passing a flag to all compiler instances. Seebuild.rustflagsfor some more ways to set flags. This string is split by whitespace; for a more robust encoding of multiple arguments, seeCARGO_ENCODED_RUSTFLAGS.CARGO_ENCODED_RUSTFLAGS— A list of custom flags separated by0x1f(ASCII Unit Separator) to pass to all compiler invocations that Cargo performs.CARGO_INCREMENTAL— If this is set to 1 then Cargo will force incremental compilation to be enabled for the current compilation, and when set to 0 it will force disabling it. If this env var isn’t present then cargo’s defaults will otherwise be used. See alsobuild.incrementalconfig value.CARGO_CACHE_RUSTC_INFO— If this is set to 0 then Cargo will not try to cache compiler version information.HTTPS_PROXYorhttps_proxyorhttp_proxy— The HTTP proxy to use, seehttp.proxyfor more detail.HTTP_TIMEOUT— The HTTP timeout in seconds, seehttp.timeoutfor more detail.TERM— If this is set todumb, it disables the progress bar.BROWSER— The web browser to execute to open documentation withcargo doc’s--openflag, seedoc.browserfor more details.RUSTFMT— Instead of runningrustfmt,cargo fmtwill execute this specifiedrustfmtinstance instead.
組態環境變數
Cargo reads environment variables for some configuration values. See the configuration chapter for more details. In summary, the supported environment variables are:
CARGO_ALIAS_<name>— Command aliases, seealias.CARGO_BUILD_JOBS— Number of parallel jobs, seebuild.jobs.CARGO_BUILD_RUSTC— Therustcexecutable, seebuild.rustc.CARGO_BUILD_RUSTC_WRAPPER— Therustcwrapper, seebuild.rustc-wrapper.CARGO_BUILD_RUSTC_WORKSPACE_WRAPPER— Therustcwrapper for workspace members only, seebuild.rustc-workspace-wrapper.CARGO_BUILD_RUSTDOC— Therustdocexecutable, seebuild.rustdoc.CARGO_BUILD_TARGET— 預設的目標平臺,請參見build.target。CARGO_BUILD_TARGET_DIR— 預設的輸出目錄,請參見build.target-dir。CARGO_BUILD_BUILD_DIR— 預設的建置目錄,請參見build.build-dir。CARGO_BUILD_RUSTFLAGS— 額外的rustc旗標,請參見build.rustflags。CARGO_BUILD_RUSTDOCFLAGS— 額外的rustdoc旗標,請參見build.rustdocflags。CARGO_BUILD_INCREMENTAL— Incremental compilation, seebuild.incremental.CARGO_BUILD_DEP_INFO_BASEDIR— Dep-info relative directory, seebuild.dep-info-basedir.CARGO_CACHE_AUTO_CLEAN_FREQUENCY— Configures how often automatic cache cleaning runs, seecache.auto-clean-frequency.CARGO_CARGO_NEW_VCS— The default source control system withcargo new, seecargo-new.vcs.CARGO_FUTURE_INCOMPAT_REPORT_FREQUENCY— How often we should generate a future incompat report notification, seefuture-incompat-report.frequency.CARGO_HTTP_DEBUG— 啟用 HTTP 除錯,請參見http.debug。CARGO_HTTP_PROXY— 啟用 HTTP 代理,請參見http.proxy。CARGO_HTTP_TIMEOUT— The HTTP timeout, seehttp.timeout.CARGO_HTTP_CAINFO— The TLS certificate Certificate Authority file, seehttp.cainfo.CARGO_HTTP_PROXY_CAINFO— The proxy TLS certificate Certificate Authority file, seehttp.proxy-cainfo.CARGO_HTTP_CHECK_REVOKE— Disables TLS certificate revocation checks, seehttp.check-revoke.CARGO_HTTP_SSL_VERSION— 使用的 TLS 版本,請參見http.ssl-version。CARGO_HTTP_LOW_SPEED_LIMIT— The HTTP low-speed limit, seehttp.low-speed-limit.CARGO_HTTP_MULTIPLEXING— Whether HTTP/2 multiplexing is used, seehttp.multiplexing.CARGO_HTTP_USER_AGENT— The HTTP user-agent header, seehttp.user-agent.CARGO_INSTALL_ROOT—cargo install的預設目錄,請參見install.root。CARGO_NET_RETRY— Number of times to retry network errors, seenet.retry.CARGO_NET_GIT_FETCH_WITH_CLI— Enables the use of thegitexecutable to fetch, seenet.git-fetch-with-cli.CARGO_NET_OFFLINE— 離線模式,請參見net.offline。CARGO_PROFILE_<name>_BUILD_OVERRIDE_<key>— Override build script profile, seeprofile.<name>.build-override.CARGO_PROFILE_<name>_CODEGEN_UNITS— Set code generation units, seeprofile.<name>.codegen-units.CARGO_PROFILE_<name>_DEBUG— What kind of debug info to include, seeprofile.<name>.debug.CARGO_PROFILE_<name>_DEBUG_ASSERTIONS— Enable/disable debug assertions, seeprofile.<name>.debug-assertions.CARGO_PROFILE_<name>_INCREMENTAL— Enable/disable incremental compilation, seeprofile.<name>.incremental.CARGO_PROFILE_<name>_LTO— Link-time optimization, seeprofile.<name>.lto.CARGO_PROFILE_<name>_OVERFLOW_CHECKS— Enable/disable overflow checks, seeprofile.<name>.overflow-checks.CARGO_PROFILE_<name>_OPT_LEVEL— Set the optimization level, seeprofile.<name>.opt-level.CARGO_PROFILE_<name>_PANIC— The panic strategy to use, seeprofile.<name>.panic.CARGO_PROFILE_<name>_RPATH— The rpath linking option, seeprofile.<name>.rpath.CARGO_PROFILE_<name>_SPLIT_DEBUGINFO— Controls debug file output behavior, seeprofile.<name>.split-debuginfo.CARGO_PROFILE_<name>_STRIP— Controls stripping of symbols and/or debuginfos, seeprofile.<name>.strip.CARGO_REGISTRIES_<name>_CREDENTIAL_PROVIDER— Credential provider for a registry, seeregistries.<name>.credential-provider.CARGO_REGISTRIES_<name>_INDEX— URL of a registry index, seeregistries.<name>.index.CARGO_REGISTRIES_<name>_TOKEN— Authentication token of a registry, seeregistries.<name>.token.CARGO_REGISTRY_CREDENTIAL_PROVIDER— Credential provider for crates.io, seeregistry.credential-provider.CARGO_REGISTRY_DEFAULT— Default registry for the--registryflag, seeregistry.default.CARGO_REGISTRY_GLOBAL_CREDENTIAL_PROVIDERS— Credential providers for registries that do not have a specific provider defined. Seeregistry.global-credential-providers.CARGO_REGISTRY_TOKEN— Authentication token for crates.io, seeregistry.token.CARGO_TARGET_<triple>_LINKER— The linker to use, seetarget.<triple>.linker. The triple must be converted to uppercase and underscores.CARGO_TARGET_<triple>_RUNNER— The executable runner, seetarget.<triple>.runner.CARGO_TARGET_<triple>_RUSTFLAGS— 目標額外的rustc旗標,請參見target.<triple>.rustflags。CARGO_TERM_QUIET— Quiet mode, seeterm.quiet.CARGO_TERM_VERBOSE— The default terminal verbosity, seeterm.verbose.CARGO_TERM_COLOR— The default color mode, seeterm.color.CARGO_TERM_PROGRESS_WHEN— The default progress bar showing mode, seeterm.progress.when.CARGO_TERM_PROGRESS_WIDTH— The default progress bar width, seeterm.progress.width.
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 test as 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, "".
CARGO— 執行建置的cargo二進位路徑。CARGO_MANIFEST_DIR— The directory containing the manifest of your package.CARGO_MANIFEST_PATH— The path to the manifest of your package.CARGO_PKG_VERSION— 軟體包的完整版本。CARGO_PKG_VERSION_MAJOR— 軟體包的主要版本。CARGO_PKG_VERSION_MINOR— 軟體包的次要版本。CARGO_PKG_VERSION_PATCH— 軟體包的補釘版本。CARGO_PKG_VERSION_PRE— 軟體包的預發行版本。CARGO_PKG_AUTHORS— Colon separated list of authors from the manifest of your package.CARGO_PKG_NAME— 軟體包的名稱。CARGO_PKG_DESCRIPTION— The description from the manifest of your package.CARGO_PKG_HOMEPAGE— The home page from the manifest of your package.CARGO_PKG_REPOSITORY— The repository from the manifest of your package.CARGO_PKG_LICENSE— The license from the manifest of your package.CARGO_PKG_LICENSE_FILE— The license file from the manifest of your package.CARGO_PKG_RUST_VERSION— The Rust version from the manifest of your package. Note that this is the minimum Rust version supported by the package, not the current Rust version.CARGO_PKG_README— 您的軟體包中 README 檔案的路徑。CARGO_CRATE_NAME— The name of the crate that is currently being compiled. It is the name of the Cargo target with-converted to_, such as the name of the library, binary, example, integration test, or benchmark.CARGO_BIN_NAME— The name of the binary that is currently being compiled. Only set for binaries or binary examples. This name does not include any file extension, such as.exe.OUT_DIR— If the package has a build script, this is set to the folder where the build script should place its output. See below for more information. (Only set during compilation.) Cargo does not guarantee that this directory is empty, and it is not cleaned between builds.CARGO_BIN_EXE_<name>— The absolute path to a binary target’s executable. This is only set when building an integration test or benchmark. This may be used with theenvmacro to find the executable to run for testing purposes. The<name>is the name of the binary target, exactly as-is. For example,CARGO_BIN_EXE_my-programfor a binary namedmy-program. Binaries are automatically built when the test is built, unless the binary has required features that are not enabled.CARGO_PRIMARY_PACKAGE— This environment variable will be set if the package being built is primary. Primary packages are the ones the user selected on the command-line, either with-pflags or the defaults based on the current directory and the default workspace members. This variable will not be set when building dependencies, unless a dependency is also a workspace member that was also selected on the command-line. This is only set when compiling the package (not when running binaries or tests).CARGO_TARGET_TMPDIR— Only set when building integration test or benchmark code. This is a path to a directory inside the target directory where integration tests or benchmarks are free to put any data needed by the tests/benches. Cargo initially creates this directory but doesn’t manage its content in any way, this is the responsibility of the test code.
動態程式庫路徑
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:
- Windows:
PATH - macOS:
DYLD_FALLBACK_LIBRARY_PATH - Unix:
LD_LIBRARY_PATH - AIX:
LIBPATH
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 會引入以下路徑:
- Search paths included from any build script with the
rustc-link-searchinstruction. Paths outside of thetargetdirectory are removed. It is the responsibility of the user running Cargo to properly set the environment if additional libraries on the system are needed in the search path. - The base output directory, such as
target/debug, and the “deps” directory. This is mostly for support of proc-macros. - The rustc sysroot library path. This generally is not important to most users.
Cargo 為建置腳本設定的環境變數
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 現在將包含 OUT_DIR 的值。
-
CARGO— 執行建置的cargo二進位路徑。 -
CARGO_MANIFEST_DIR— The directory containing the manifest for the package being built (the package containing the build script). Also note that this is the value of the current working directory of the build script when it starts. -
CARGO_MANIFEST_PATH— The path to the manifest of your package. -
CARGO_MANIFEST_LINKS— 清單links值。 -
CARGO_MAKEFLAGS— Contains parameters needed for Cargo’s jobserver implementation to parallelize subprocesses. Rustc or cargo invocations from build.rs can already readCARGO_MAKEFLAGS, but GNU Make requires the flags to be specified either directly as arguments, or through theMAKEFLAGSenvironment variable. Currently Cargo doesn’t set theMAKEFLAGSvariable, but it’s free for build scripts invoking GNU Make to set it to the contents ofCARGO_MAKEFLAGS. -
CARGO_FEATURE_<name>— For each activated feature of the package being built, this environment variable will be present where<name>is the name of the feature uppercased and having-translated to_. -
CARGO_CFG_<cfg>— For each configuration option of the package being built, this environment variable will contain the value of the configuration, where<cfg>is the name of the configuration uppercased and having-translated to_. Boolean configurations are present if they are set, and not present otherwise. Configurations with multiple values are joined to a single variable with the values delimited by,. This includes values built-in to the compiler (which can be seen withrustc --print=cfg) and values set by build scripts and extra flags passed torustc(such as those defined inRUSTFLAGS). Some examples of what these variables are:CARGO_CFG_FEATURE— Each activated feature of the package being built.CARGO_CFG_UNIX— Set on unix-like platforms.CARGO_CFG_WINDOWS— Set on windows-like platforms.CARGO_CFG_TARGET_FAMILY=unix,wasm— The target family.CARGO_CFG_TARGET_OS=macos— 目標作業系統。CARGO_CFG_TARGET_ARCH=x86_64— CPU 目標架構。CARGO_CFG_TARGET_VENDOR=apple— The target vendor.CARGO_CFG_TARGET_ENV=gnu— 目標環境 ABI。CARGO_CFG_TARGET_ABI=eabihf— 目標 ABI。CARGO_CFG_TARGET_POINTER_WIDTH=64— The CPU pointer width.CARGO_CFG_TARGET_ENDIAN=little— The CPU target endianness.CARGO_CFG_TARGET_FEATURE=mmx,sse— List of CPU target features enabled.
Note that different target triples have different sets of
cfgvalues, hence variables present in one target triple might not be available in the other.Some cfg values like
testare not available. -
OUT_DIR— the folder in which all output and intermediate artifacts should be placed. This folder is inside the build directory for the package being built, and it is unique for the package in question. Cargo does not clean or reset this directory between builds, and its contents may persist across rebuilds. Build scripts should not assume thatOUT_DIRis empty, and are responsible for managing or cleaning up any files they create. -
TARGET— the target triple that is being compiled for. Native code should be compiled for this triple. See the Target Triple description for more information. -
HOST— the host triple of the Rust compiler. -
NUM_JOBS— the parallelism specified as the top-level parallelism. This can be useful to pass a-jparameter to a system likemake. Note that care should be taken when interpreting this environment variable. For historical purposes this is still provided but recent versions of Cargo, for example, do not need to runmake -j, and instead can set theMAKEFLAGSenv var to the content ofCARGO_MAKEFLAGSto activate the use of Cargo’s GNU Make compatible jobserver for sub-make invocations. -
DEBUG—trueif anydebuginformation will be generated andfalseotherwise. -
OPT_LEVEL— values of the correspondingopt-levelvariable for the profile currently being built. -
PROFILE—releasefor release builds,debugfor other builds. This is determined based on if the profile inherits from thedevorreleaseprofile. Using this environment variable is not recommended. Using other environment variables likeOPT_LEVELprovide a more correct view of the actual settings being used. -
DEP_<links>_<key>— For more information about this set of environment variables, see build script documentation aboutlinks. -
RUSTC,RUSTDOC— the compiler and documentation generator that Cargo has resolved to use, passed to the build script so it might use it as well. -
RUSTC_WRAPPER— therustcwrapper, if any, that Cargo is using. Seebuild.rustc-wrapper. -
RUSTC_WORKSPACE_WRAPPER— therustcwrapper, if any, that Cargo is using for workspace members. Seebuild.rustc-workspace-wrapper. -
RUSTC_LINKER— The path to the linker binary that Cargo has resolved to use for the current target, if specified. The linker can be changed by editing.cargo/config.toml; see the documentation about cargo configuration for more information. -
CARGO_ENCODED_RUSTFLAGS— extra flags that Cargo invokesrustcwith, separated by a0x1fcharacter (ASCII Unit Separator). Seebuild.rustflags. Note that since Rust 1.55,RUSTFLAGSis removed from the environment; scripts should useCARGO_ENCODED_RUSTFLAGSinstead. -
CARGO_PKG_<var>— The package information variables, with the same names and values as are provided during crate building.
Environment variables Cargo sets for cargo test
Cargo sets several environment variables when tests are run. You can retrieve the values when the tests are run:
use std::env;
let out_dir = env::var("CARGO_BIN_EXE_foo").unwrap();
CARGO_BIN_EXE_<name>— The absolute path to a binary target’s executable. This is only set when running an integration test or benchmark. The<name>is the name of the binary target, exactly as-is. For example,CARGO_BIN_EXE_my-programfor a binary namedmy-program. Binaries are automatically built when the test is built, unless the binary has required features that are not enabled.
Cargo 為第三方子命令設定的環境變數
Cargo exposes this environment variable to 3rd party subcommands (ie. programs named cargo-foobar placed in $PATH):
CARGO— 執行建置的cargo二進位路徑。CARGO_MAKEFLAGS— Contains parameters needed for Cargo’s jobserver implementation to parallelize subprocesses. This is set only when Cargo detects the existence of a jobserver.
For extended information about your environment you may run cargo metadata.