我们如何检测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");
}
}