How do I use conditional compilation with `cfg` and Cargo?

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.

Leave a Comment