如何在Rust中使用条件编译宏的示例

问题描述 投票:3回答:1

我跟随quite a bitthe documentation并尝试reuse an example,但我无法让我的代码工作。

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

[package]
name = "Blahblah"
version = "0.3.0"
authors = ["ergh <[email protected]"]
[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!语句都在评估为false。为什么?

我读过Conditional compilation in Rust 0.10?,我知道它并不完全重复,因为我正在寻找一个有效的例子。

rust
1个回答
5
投票

测试特征的正确方法是feature = "name",如果你滚动一点,你可以在the documentation you linked中看到:

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

[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")

© www.soinside.com 2019 - 2024. All rights reserved.