How to get the value of the configuration flag?

Is there any way to get the value of the configuration icon ? For example, I would like to get the target_os value as str / String , without resorting to the following if-else-if chain:

 if cfg!(target_os = "windows") { "windows" } else if cfg!(target_os = "linux") { "linux" // ... } else { "unknown" } 
+5
source share
1 answer

No. You can get some of them by tricking Cargo to tell you. If you put the following in 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 that Cargo knows about. panic! it’s just there as an easy way to get Cargo to actually show the result, rather than hide it. For reference, the result is as follows:

  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 ​​of interest to you from this list and upload them to the generated source file, which can then be imported (using #[path] or include! ) Into the source package.

+4
source

Source: https://habr.com/ru/post/1266781/


All Articles