【问题标题】:Combine Conditional Compilation Parameters组合条件编译参数
【发布时间】:2021-08-01 06:48:35
【问题描述】:

我试图在两个条件下有条件地编译一段代码:

  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"); }

【问题讨论】:

标签: linux rust rust-cargo


【解决方案1】:

The conditional compilation system offers a full set of Boolean operators under the names any, all, and 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");
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-03
    • 1970-01-01
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多