yexuanyang

导航

 

link: Conditional compilation - The Rust Reference

rust cfg条件编译

编译谓词,all any not
编译选项 , key = value,=两边的空白字符被忽略。
#[cfg()]或者cfg!()或者--cfg指定rustc编译选项,这三种方式可以条件编译

指定条件编译的mod来源路径

#[cfg_attr(target_os = "linux", path = "linux.rs")]
#[cfg_attr(windows, path = "windows.rs")]
mod os;

一个属性可以被分割成多个属性

#[cfg_attr(feature = "magic", sparkles, crackles)]
fn bewitched() {}

// When the `magic` feature flag is enabled, the above will expand to:
#[sparkles]
#[crackles]
fn bewitched() {}

常见的编译选项:
target_os
target_arch
target_family -> 指定unix系或者windows系
unix windows -> 如果target_family = "unix"那么unix 被指定,windows类似
target_env -> 指定ABI,比如msvc gnu,嵌入式ABI会简单的指定为gnu,比如gnueabihf会指定为gnu
target_endian -> 指定大小端
...

使用cfg!判断当前平台


#![allow(unused)]
fn main() {
	let machine_kind = if cfg!(unix) {
	  "unix"
	} else if cfg!(windows) {
	  "windows"
	} else {
	  "unknown"
	};
	
	println!("I'm running on a {} machine!", machine_kind);
}

posted on 2025-06-15 14:34  yexuanyang  阅读(36)  评论(0)    收藏  举报