Rust使用cfg来实现不同系统的条件编译
cfg有两种使用方法:
属性的方法 #[cfg(…)]
#[cfg(target_os = "linux")]
fn get_os_info(){println!("linux");
}
#[cfg(target_os = "windows")]
fn get_os_info() {println!("windows");
}
fn main() {
get_os_info();
}
在不同的操作系统上会编译不同的函数。
也可使用not表达式:
#[cfg(not(target_os = "linux"))]
fn get_os_info() {
println!("not linux");
}
在非 linux 系统下会编译此函数。
使用cfg宏的方法进行条件编译
fn main() {
if cfg!(target_os = "linux") { println!("linux"); } else { println!("not linux"); }
}
具体使用哪一种方法,要视情况而定。比如第二种方法不适合代码数量多的情况。
原创地址: https://www.perfcode.com/p/1554.html
如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!
txttool.com 说一段 esp56物联 查询128 IP查询