Rust 编程: 条件编译-Features

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

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

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 编译

  1. 修改 cargo.toml

[features]
myfeaone = []
myfeatwo = []

  1. 条件编译

cargo build --features="myfeaone myfeatwo"

5. 传递条件

Rust 的模块化系统: 包Packages, 箱Crates, 和模块Modules

  • packages: 通过cargo new 创建;
  • crates: 通过cargo new --lib 创建。有根包和子包。即一个根包下可以包含多个子包。
  • modules: 通过关键字mod加模块定义

Rust/Cargo 自设条件如何从根包传递到子包?

  1. 修改根包 cargo.toml

[features]
myfeaone = ["subcrateone/myfeaone", "subcratetwo/myfeaone"]
myfeatwo = ["subcrateone/myfeatwo", "subcratetwo/myfeatwo"]

  1. 修改子包 cargo.toml

[features]
myfeaone = []
myfeatwo = []

  1. 在根包目录下,条件编译

cargo build --features="myfeaone myfeatwo"

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值