rust条件编译

条件编译的使用方法

两种操作方式进行rust的条件编译

  1. cfg属性:在属性的位置标注 #[cfg(...)]
    例如
#[cfg(target_os = "windows")]
mod os {
  // windows相关结构方法代码
  ...
} 
#[cfg(target_os = "linux")]
mod os {
  // linux相关结构方法代码
  ...
} 
  1. cfg宏:在条件表达式中使用cfg!(...)
    例如
if cfg!(target_os = "windows") {
  // windows系统要执行的代码段
} else if cfg!(target_os = "linux") {
  // linux系统要执行的代码段
}

除了按系统类型条件编译外,rust还支持以下类型条件:

  • debug_assertions - 若没有开启编译优化时就会成立。
  • target_arch = "..." - 目标平台的CPU架构,包括但不限于x86, x86_64, mips, powerpc, arm或aarch64。
  • target_endian = "..." - 目标平台的大小端,包括big和little。
  • target_env = "..." - 表示使用的运行库,比如musl表示使用的是MUSL的libc实现, msvc表示使用微软的MSVC,gnu表示使用GNU的实现。 但在部分平台这个数据是空的。
  • target_family = "..." - 表示目标操作系统的类别,比如windows和unix。这个属性可以直接作为条件使用,如#[unix],#[cfg(unix)]。
  • target_os = "..." - 目标操作系统,包括但不限于windows, macos, ios, linux, android, freebsd, dragonfly, bitrig, openbsd, netbsd。
  • target_pointer_width = "..." - 目标平台的指针宽度,一般就是32或64。
  • target_vendor = "..." - 生产商,例如apple, pc或大多数Linux系统的unknown。
  • test - 当启动了单元测试时(即编译时加了--test参数,或使用cargo test)。
    还可以根据一个条件去设置另一个条件,使用cfg_attr,如

此外rust支持使用any,all,not等限定条件编译的条件之间的关系

比如

// 这个函数仅当操作系统不是Linux 时才会编译
#[cfg(not(target_os = "linux"))]
fn not_linux() {
    println!("You are not running linux!");
}

// 这个函数当为macos**或者**ios时才会编译
#[cfg(any(target_os = "macos", target_os="ios"))]
fn you_are_apple {
  println!("You are running macos or ios");
}

// 这个函数当为32位的Unix系统时才会编译
#[cfg(all(unix, target_pointer_width = "32"))]
fn on_32bit_unix() {
  println!("You are running 32 bit unix");
}

自定义条件

自定义条件的属性标注方式如下:

#[cfg(some_condition)]
fn conditional_function() {
    println!("condition met!")
}

fn main() {
    conditional_function();
}

target_os等rustc已经支持的条件可以隐式判断进行编译,而自定义条件,需要在编译需要显式指定编译条件。

  1. 使用rustc 编译
$ rustc custom.rs && ./custom
No such file or directory (os error 2)

以上编译方式会报错,因为直接执行编译找不到条件下的conditional_function方法
需要使用以下方法编译:

$ rustc --cfg some_condition custom.rs && ./custom
condition met!
  1. 使用cargo编译
    首先,需要在cargo.toml文件里增加以下内容
[features]
some_condition = []

直接执行cargo build会报错找不到方法
正确方法应该使用以下方式编译:

$ cargo build --features some_condition

你可能感兴趣的:(rust条件编译)