Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/email/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我们如何检测Rust中的开发操作系统类型(而不是目标操作系统)?_Rust_Cross Compiling - Fatal编程技术网

我们如何检测Rust中的开发操作系统类型(而不是目标操作系统)?

我们如何检测Rust中的开发操作系统类型(而不是目标操作系统)?,rust,cross-compiling,Rust,Cross Compiling,检测目标操作系统的方法有很多,例如,#[cfg(windows)],#[cfg(unix)],std::env::consts::OS。对于交叉编译,我们如何检测Rust程序编译的操作系统?由于build.rs是在工作站(而不是目标)上运行的,我想它可以检测一些与工作站相关的属性(cfg),这些属性可以在目标相关的代码中进行测试 例如,这里有一个build.rs脚本,用于检测工作站上的特定文件 fn main() { // detected on the workstation (not

检测目标操作系统的方法有很多,例如,
#[cfg(windows)]
#[cfg(unix)]
std::env::consts::OS
。对于交叉编译,我们如何检测Rust程序编译的操作系统?

由于
build.rs
是在工作站(而不是目标)上运行的,我想它可以检测一些与工作站相关的属性(
cfg
),这些属性可以在目标相关的代码中进行测试

例如,这里有一个
build.rs
脚本,用于检测工作站上的特定文件

fn main() {
    // detected on the workstation (not the target)
    if let Ok(_attr) = std::fs::metadata("dummy_file.txt") {
        println!("cargo:rustc-cfg=detected");
    }
    if cfg!(windows) {
        println!("cargo:rustc-cfg=from_windows");
    }
    if cfg!(unix) {
        println!("cargo:rustc-cfg=from_unix");
    }
}
然后,
src/main.rs
可以测试检测到的特性

#[cfg(detected)]
fn hello() {
    if cfg!(from_windows) {
        println!("hello from windows with detected file");
    }
    if cfg!(from_unix) {
        println!("hello from unix with detected file");
    }
}

#[cfg(not(detected))]
fn hello() {
    if cfg!(from_windows) {
        println!("hello from windows");
    }
    if cfg!(from_unix) {
        println!("hello from unix");
    }
}

fn main() {
    // run on the target (not the workstation)
    hello();
}
根据生成项目时工作站上是否存在
dummy_file.txt
,目标的生成二进制文件将使用
hello()
的一个版本或另一个版本。
这两个功能中的每一个都可以根据工作站上的操作系统来调整其行为。

您真的不能
fn main() {
    // detected on the workstation (not the target)
    if let Ok(_attr) = std::fs::metadata("dummy_file.txt") {
        println!("cargo:rustc-cfg=detected");
    }
    if cfg!(windows) {
        println!("cargo:rustc-cfg=from_windows");
    }
    if cfg!(unix) {
        println!("cargo:rustc-cfg=from_unix");
    }
}