Example of how to use Conditional Compilation Macr

2020-01-27 08:17发布

I've followed quite a bit of the documentation and tried to reuse an example, but I can't get my code to work.

My Cargo.toml looks like this:

[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=[]

I'd like to test my code locally with a different buffer origin than mmap based on what feature configuration I pass to the cargo build command. I have this in my code:

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

The compiler doesn't see the code in either of the if statement bodies, so I know that both of the cfg! statements are evaluating to false. Why?

I've read Conditional compilation in Rust 0.10? and I know it's not an exact duplicate because I'm looking for a functioning example.

标签: rust
1条回答
迷人小祖宗
2楼-- · 2020-01-27 08:31

The correct way to test for a feature is feature = "name", as you can see in the documentation you linked if you scroll a bit:

As for how to enable or disable these switches, if you’re using Cargo, they get set in the [features] section of your 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 = []

When you do this, Cargo passes along a flag to rustc:

--cfg feature="${feature_name}"

The sum of these cfg flags will determine which ones get activated, and therefore, which code gets compiled. Let’s take this code:

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

In your case using the cfg! macro, this would map to cfg!(feature = "foo").

查看更多
登录 后发表回答