linux - 组合条件编译参数
问题描述
在给定两个条件的情况下,我正在尝试有条件地编译代码的某个部分:
- 构建是否通过 Linux 完成
- 用户指定的功能标志“模拟”是否设置为真
我的精简版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"); }
解决方案
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");
}
推荐阅读
- python - 在对象列表中选择具有最大属性的对象
- angular - 将 Angular http 帖子拆分为多个调用
- javascript - Parse 服务器中没有这样的文件或目录 - 云代码
- python - 您必须使用 dtype int32 为占位符张量“Placeholder”提供一个值
- flutter - FirebaseDynamicLinks.instance.getInitialLink() 在 Android 上总是返回 null
- rust - 是否可以在 Rust 中编写 Quake 的快速 InvSqrt() 函数?
- oozie - Oozie 动作将进入下一个动作,认为动作状态为失败
- javascript - 如何在ajax成功回调中更改日期格式
- javascript - 如何设置交叉环境变量以在提交前开始测试?
- python - 将嵌套字典中的值和键映射到列