Specify features for dependencies conditionally

How to pass features conditionally to dependencies only if they are specified by the consumer of the enclosing package?

Here's the problem expressed as a dummy example workspace:

Summary:

  • A metacrate, c1, has a feature c1_some_feature. c1 depends on c2
  • c2 has this same feature and depends on c3
  • c3 too has this same feature
  • The feature c1_some_feature is optional
  • When I ran cargo run c1 --features c1_some_feature, I got this:
# got
called c3::f() without c1_some_feature

# expected
called c3::f() with c1_some_feature

Is there a way to solve this?

You should give your feature in c1 a dependency on the feature flag in c2.

[dependencies]
c2 = { path = "../c2" }

[features]
c1_some_feature = ["c2/c1_some_feature"]

You can read more about ways to specify feature flags in the cargo reference.

1 Like

Nice! I wonder why it did no effect.

I put this in c1/Cargo.toml:

[features]
c1_some_feature = ["c2/c1_some_feature"]

c2/Cargo.toml:

[features]
c1_some_feature = ["c3/c1_some_feature"]

Running with:

cargo run c1 --features c1_some_feature

Updated links:

c3/Cargo.toml is same, with an empty features.c1_some_feature = []

The problem is, I need to specify the argument -p (or --package) when building:

# this
cargo run -p c1 --features c1_some_feature

# not this
cargo run c1 --features c1_some_feature

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.