[英]Example of how to use Conditional Compilation Macros in Rust
我已經遵循了相當多的文檔並嘗試重用一個示例,但我無法讓我的代碼工作。
我的 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!
陳述評估為假。 為什么?
我讀過Rust 0.10 中的條件編譯? 我知道這不是完全重復的,因為我正在尋找一個有效的例子。
測試功能的正確方法是feature = "name"
,正如您可以在鏈接的文檔中看到的那樣,如果您稍微滾動一下:
至於如何啟用或禁用這些開關,如果您使用 Cargo,它們將在
Cargo.toml
的[features]
部分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")
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.