Disable feature for example

Ref: Enable feature for an example

I have a number of libraries, and they have examples. I want one of the examples to compile with a feature off, so that it doesn't pull in another library. This is for testing the library crate independently.

So, I have a mod.rs file:

#[cfg_attr(not (feature="usescene"), path="shimscenedummy.rs")]    // if usescene is off, use the dummy version
mod shimscene;

and in the library crate's Cargo.toml file, I have

default = []
usescene = ["libscene"]

name = "mapmaker"
path = "src/examples/mapmaker/main.rs"

libscene = { version = "*", path = "../libscene", optional=true }

The idea is that the examples should be built with "usescene" off, not pull in the "libscene" library, and the #cfg should use the "shimscenedummy" path. But it's puling in "shimscene". So what's turning on "usescene"?

There's a root Cargo.toml file, but it's just a workspace. No features. Building the main program from the workspace does turn on "usescene". Did that somehow affect the examples of the library crate?

Heya, it's hard to be sure without seeing the repo and commands being run, but some possibilities:

  • you're testing lib_a, but lib_a depends on lib_a with "libscene" enabled, and lib_b is included in the compilation. e.g. a workspace wide compilation that includes lib_b
  • the command being run may be a tool that enables --all-features

Yes, it's hard to repo this without a huge amount of stuff.

Possible. Here's the entire workspace Cargo.toml:

resolver = "2"
members = [

default-members = [

Ah. I may be misunderstanding something fundamental here. Does a workspace build always build only one version of each library? Or are multiple versions built depending on the dependencies of each target? What I'm trying to do here is build three executables, one "bin" target, "sharpview", and two "examples" targets, one of which is "mapmaker". These need "libscene" compiled with different features. Cargo is able to build the same package with different versions, so I just assumed it could build the same package with different features. But maybe I'm wrong about that.

The command being run is cargo build --examples at the workspace level.

No. Feature unification is supposed to happen.

You can not produce one, single, binary which supports interfaces from two version thus cargo doesn't have a choice.

Also: ten versions of crates lead to ten possible build, ten features can lead to thousand configurations (and twenty would mean million!) thus it's natural to treat features and versions differently.

Yeah, overnight I figured that out. If I want examples with specific features, I have to promote them to top-level targets and give them their own Cargo.toml file.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.