How to obtain the value of a configuration flag?

No. You can get some of them by tricking Cargo into telling you. If you place the following into a build script:

use std::env;

fn main() {
    for (key, value) in env::vars() {
        if key.starts_with("CARGO_CFG_") {
            println!("{}: {:?}", key, value);
        }
    }
    panic!("stop and dump stdout");
}

...it will display the cfg flags Cargo is aware of. The panic! is just there as an easy way to get Cargo to actually show the output instead of hiding it. For reference, the output this produces looks like this:

   Compiling dump-cfg v0.1.0 (file:///F:/Programming/Rust/sandbox/cargo-test/dump-cfg)
error: failed to run custom build command for `dump-cfg v0.1.0 (file:///F:/Programming/Rust/sandbox/cargo-test/dump-cfg)`
process didn't exit successfully: `F:\Programming\Rust\sandbox\cargo-test\dump-cfg\target\debug\build\dump-cfg-8b04f9ac3818f82a\build-script-build` (exit code: 101)
--- stdout
CARGO_CFG_TARGET_POINTER_WIDTH: "64"
CARGO_CFG_TARGET_ENV: "msvc"
CARGO_CFG_TARGET_OS: "windows"
CARGO_CFG_TARGET_ENDIAN: "little"
CARGO_CFG_TARGET_FAMILY: "windows"
CARGO_CFG_TARGET_ARCH: "x86_64"
CARGO_CFG_TARGET_HAS_ATOMIC: "16,32,64,8,ptr"
CARGO_CFG_TARGET_FEATURE: "sse,sse2"
CARGO_CFG_WINDOWS: ""
CARGO_CFG_TARGET_VENDOR: "pc"
CARGO_CFG_DEBUG_ASSERTIONS: ""

--- stderr
thread 'main' panicked at 'stop', build.rs:9
note: Run with `RUST_BACKTRACE=1` for a backtrace.

You can extract the values you're interested in from this list, and dump them to a generated source file, which you can then import (using #[path] or include!) into your package's source.


For target_os specifically, and also for just target_family and target_arch, there are corresponding &str constants in std::env::consts::{OS, FAMILY, ARCH}.

Tags:

Rust