如何获取配置标志的值?

时间:2017-04-16 07:59:04

标签: rust

有没有办法获得configuration flag的价值?例如,我希望将target_os的值设为str / String,而不使用以下if-else-if链:

if cfg!(target_os = "windows") {
    "windows"
} else if cfg!(target_os = "linux") {
    "linux"
// ...
} else {
    "unknown"
}

2 个答案:

答案 0 :(得分:4)

没有。你可以通过欺骗货物告诉你,获得一些。如果您将以下内容放入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");
}

...它将显示Cargo知道的cfg标志。 panic!只是让货物实际显示输出而不是隐藏输出的简单方法。作为参考,它产生的输出如下所示:

   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.

您可以从此列表中提取您感兴趣的值,并将它们转储到生成的源文件中,然后可以将其导入(使用#[path]include!)到包的源代码中。

答案 1 :(得分:3)

特别是对于target_os,以及仅target_familytarget_arch,在std::env::consts::{OS, FAMILY, ARCH}中有相应的&str常量。