I want to conditionally compile my source code using cfg
with Cargo, after Googling for a while, it seems that the solution is to use cargo --features
.
http://doc.crates.io/manifest.html
I tried adding a few
#[cfg(feature = "foo")]
in the source code and
cargo build --features foo
, but it says
Package `xxx v0.0.1 (file:///C:/yyy/xxx)` does not have these features: `foo`
How can I let cargo identify the features? Do I have to add something in Cargo.toml
?
Here's the version of rustc
and cargo
I am using:
C:\>rustc --version rustc 0.13.0-nightly (42deaa5e4 2014-12-16 17:51:23 +0000) C:\>cargo --version cargo 0.0.1-pre-nightly (5af754d 2014-12-18 01:50:48 +0000)
Conditional compilation provides a way of including or omitting selected lines of source code depending on the values of literals specified by the DEFINE directive. In this way, you can create multiple variants of the same program without the need to maintain separate source streams.
Rust has a special attribute, #[cfg] , which allows you to compile code based on a flag passed to the compiler.
You have to introduce the existing features in your Cargo.toml
.
I was able to conditionally compile by doing the following:
In Cargo.toml
, create a features
section and introduce a certain feature name:
[features] customfeature = [] # feature has no explicit dependencies
If you want your feature to have specific dependencies check the examples in the documentation.
In your code, use #[cfg(feature="customfeature")]
Run cargo build --features customfeature
Since your steps 2 & 3 seem to be fine, there must probably be a problem with your Cargo.toml
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With