首页 > 解决方案 > 组合条件编译参数

问题描述

在给定两个条件的情况下,我正在尝试有条件地编译代码的某个部分:

  1. 构建是否通过 Linux 完成
  2. 用户指定的功能标志“模拟”是否设置为真

我的精简版Cargo.toml具有这种通用结构

[package]
...

[features]
simulation = []

[dependencies]
crate1 = ...
crate2 = ...

[target.'cfg(target_os = "linux")'.dependencies]
crate3 = ...
crate4 = ...

有没有办法在我的 rust 代码中指定我希望在通过 Linux 完成构建并关闭“模拟”功能标志时编译一段代码,然后在通过构建完成时编译另一段代码开启了“模拟”功能标志的 Linux?就像是:

#[cfg(feature = "simulation")] && #[cfg(target_os = "linux")] { println!("run some code here"); }
!#[cfg(feature = "simulation)] && #[cfg(target_os = "linux")] { println!("run some other code here"); }

标签: linuxrustrust-cargo

解决方案


any条件编译系统在名称、all和下提供了一整套布尔运算符not将您的示例转换为工作语法:

#[cfg(all(feature = "simulation", target_os = "linux"))] {
    println!("run some code here");
}
#[cfg(all(not(feature = "simulation"), target_os = "linux"))] {
    println!("run some other code here");
}

如果您有复杂的条件要检查,那么您可能需要使用cfg_if宏箱来提供帮助。但是,在这种情况下,有一个体面的简化实际上可以在没有任何宏且不使用任何宏all()的情况下工作:只需嵌套条件,这样您就可以只编写一次通用的条件。

#[cfg(target_os = "linux")] {
    #[cfg(feature = "simulation")]
    println!("run some code here");

    #[cfg(not(feature = "simulation"))]
    println!("run some other code here");
}

推荐阅读