我已经关注了相当多 https://doc.rust-lang.org/reference/attributes.html#conditional-compilation of 文档 https://doc.rust-lang.org/stable/rust-by-example/attribute/cfg.html并试图重用一个例子 https://doc.rust-lang.org/book/first-edition/conditional-compilation.html,但我无法让我的代码工作。
我的 Cargo.toml 看起来像这样:
[package]
name = "Blahblah"
version = "0.3.0"
authors = ["ergh <[email protected] /cdn-cgi/l/email-protection"]
[dependencies]
[[bin]]
name = "target"
path = "src/main.rs"
[features]
default=["mmap_enabled"]
no_mmap=[]
mmap_enabled=[]
我想根据我传递给的功能配置,使用与 mmap 不同的缓冲区源在本地测试我的代码cargo build
命令。我的代码中有这个:
if cfg!(mmap_enabled) {
println!("mmap_enabled bro!");
...
}
if cfg!(no_mmap) {
println!("now it's not");
...
}
编译器看不到任何一个中的代码if
声明机构,所以我知道这两个cfg!
语句的评估结果为 false。为什么?
我读了Rust 0.10 中的条件编译? https://stackoverflow.com/questions/24297154/conditional-compilation-in-rust/我知道它不是完全重复,因为我正在寻找一个有效的示例。
测试功能的正确方法是feature = "name"
,正如你所看到的您链接的文档 https://doc.rust-lang.org/book/first-edition/conditional-compilation.html如果你滚动一下:
至于如何启用或禁用这些开关,如果您使用的是 Cargo,
他们被设置在[features] section https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section你的Cargo.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")
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)