Rust 编程: 条件编译-Features
Rust 支持条件编译,可通过两种不同的操作实现:
cfg属性:在属性位置中使用#[cfg(...)]cfg!宏:在布尔表达式中使用cfg!(...)
// 根据操作系统引用不同文件的相同模块
#[cfg_attr(target_os = "linux", path = "linux.rs")]
#[cfg_attr(windows, path = "windows.rs")]
mod os;
// 函数仅当操作系统是 Linux 的时候才会编译
#[cfg(target_os = "linux")]
fn do_on_linux() {
println!("You are running linux!")
}
// 函数仅当操作系统不是 Linux 的时候才会编译
#[cfg(not(target_os = "linux"))]
fn do_on_notlinux() {
println!("You are *not* running linux!")
}
if cfg!(target_os = "windows") {
// windows系统要执行的代码段
} else if cfg!(target_os = "linux") {
// linux系统要执行的代码段
}
// 依赖自设条件是否引用模块 foo
#[cfg(feature = "foo")]
mod foo;
1. 参考资料
2. 类型条件
Rust 预设类型条件:
- target_family : 目标操作系统的类别,比如windows和unix。这个属性可以直接作为条件使用,如#[unix],#[cfg(unix)]
- target_arch : 目标平台的CPU架构,包括但不限于x86, x86_64, mips, powerpc, arm或aarch64
- target_os : 目标操作系统,包括但不限于windows, macos, ios, linux, android, freebsd, dragonfly, bitrig, openbsd, netbsd
- target_pointer_width : 目标平台的指针宽度,一般就是32或64
- test : 启动单元测试(即编译时加了–test参数,或使用cargo test)
3. 限定条件
Rust 支持使用any,all,not等限定条件编译的条件之间的关系
4. 自设条件
// 自设条件 myfeaone 为真才会编译
#[cfg(myfeaone)]
fn do_myfeaone() {
println!("do_myfeaone!")
}
fn main() {
do_myfeaone();
if cfg!(feature = "myfeatwo") {
// 自设条件 myfeatwo 为真要执行的代码段
}
}
4.1. rustc 编译
rustc --cfg feature="myfeaone myfeatwo" demo.rs
4.2. cargo 编译
- 修改 cargo.toml
[features]
myfeaone = []
myfeatwo = []
- 条件编译
cargo build --features="myfeaone myfeatwo"
5. 传递条件
Rust 的模块化系统: 包Packages, 箱Crates, 和模块Modules
- packages: 通过cargo new 创建;
- crates: 通过cargo new --lib 创建。有根包和子包。即一个根包下可以包含多个子包。
- modules: 通过关键字mod加模块定义
Rust/Cargo 自设条件如何从根包传递到子包?
- 修改根包 cargo.toml
[features]
myfeaone = ["subcrateone/myfeaone", "subcratetwo/myfeaone"]
myfeatwo = ["subcrateone/myfeatwo", "subcratetwo/myfeatwo"]
- 修改子包 cargo.toml
[features]
myfeaone = []
myfeatwo = []
- 在根包目录下,条件编译
cargo build --features="myfeaone myfeatwo"

本文深入探讨Rust的条件编译特性,包括类型条件如target_family、target_arch和target_os,以及如何在属性和宏中使用它们。文章还详细介绍了限定条件、自设条件(如rustc和cargo编译配置),并讨论了条件编译如何在Rust的模块化系统中,尤其是从根包传递到子包的方式。
625

被折叠的 条评论
为什么被折叠?



