【问题标题】:Example of how to use Conditional Compilation Macros in Rust如何在 Rust 中使用条件编译宏的示例
【发布时间】:2016-01-13 21:25:14
【问题描述】:

我已关注quite a bitthe documentation 并尝试关注reuse an example,但我的代码无法正常工作。

我的 Cargo.toml 看起来像这样:

[package]
name = "Blahblah"
version = "0.3.0"
authors = ["ergh <derngummit@ahwell.com"]
[dependencies]

[[bin]]
name = "target"
path = "src/main.rs"

[features]
default=["mmap_enabled"]
no_mmap=[]
mmap_enabled=[]

我想根据我传递给cargo build 命令的功能配置,使用不同于 mmap 的缓冲区来源在本地测试我的代码。我的代码中有这个:

if cfg!(mmap_enabled) {
    println!("mmap_enabled bro!");
    ...
}
if cfg!(no_mmap) {
    println!("now it's not");
    ...
}

编译器在if 语句体中都看不到代码,所以我知道cfg! 语句的计算结果都是假的。为什么?

我已阅读 Conditional compilation in Rust 0.10?,我知道这不是完全重复的,因为我正在寻找一个有效的示例。

【问题讨论】:

  • 顺便说一下,互斥功能应该使用单个功能而不是两个独立的功能来完成,例如测试feature = "mmap"not(feature = "mmap")。具体来说,crate 的用户可以同时启用no_mmapmmap_enabled,这似乎是有问题的。
  • 我曾考虑过这一点,1) 包是内部的,2) 代码是独占的,也就是说如果另一个是,则不评估一个。
  • 酷!听起来你已经掌控了一切。 (只是确保您知道权衡取舍。)

标签: rust


【解决方案1】:

测试功能的正确方法是feature = "name",如果您稍微滚动一下,您可以在the documentation you linked 中看到:

至于如何启用或禁用这些开关,如果您使用 Cargo, 它们被设置在你的Cargo.toml[features] section 中:

[features]
# no features by default
default = []

# Add feature "foo" here, then you can use it. 
# Our "foo" feature depends on nothing else.
foo = []

当你这样做时,Cargo 将一个标志传递给rustc

--cfg feature="${feature_name}"

这些cfg 标志的总和将决定激活哪些标志, 因此,哪些代码被编译。让我们看看这段代码:

#[cfg(feature = "foo")]
mod foo {
}

在您使用cfg! 宏的情况下,这将映射到cfg!(feature = "foo")

【讨论】:

  • 这就是您包含或排除整个模块的方式。但是我有一小段代码必须在函数中间进行交换。这样语法和定义就行不通了。
  • 我明白了。我在这里强调的是如何测试 feature 的语法,即 cfg 中的东西。应该是feature = "name",而不仅仅是cfg(name)
  • 当您写包含该问题的回复时,我实际上是在为我自己的问题写一个答案。您指出了正确的方法。
猜你喜欢
  • 1970-01-01
  • 2023-03-16
  • 2020-01-29
  • 2015-02-11
  • 2022-07-19
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
相关资源
最近更新 更多