0

My project has crate A and crate B defined. Crate B defines a feature b_feature:

# B/Cargo.toml

[features]
b_feature = []

Crate A depends on crate B. I would like to use b_feature in the code of crate A without introducing new feature in crate A:

// Code in crate A
#[cfg(feature = "<some path to b_feature>")]
// Conditionally compiled code below

Is this at all possible? Ideally I would like to do something like this:

// Code in crate A that directly checks b_feature in B
#[cfg(feature = "<B/b_feature>")]
// Conditionally compiled code below

I am trying to avoid a situation where I have to 'reintroduce' feature in crate A:

# A/Cargo.toml

[dependencies]
B = ...

[features]
b_feature = ["B/b_feature"]
tkachuko
  • 1,956
  • 1
  • 13
  • 20
  • Does this answer your question? [How do I 'pass down' feature flags to subdependencies in Cargo?](https://stackoverflow.com/questions/40021555/how-do-i-pass-down-feature-flags-to-subdependencies-in-cargo) – Ömer Erden Sep 07 '22 at 06:31
  • I don't think so. To my best understanding the answer suggest that crate `A` has to introduce its own feature that depends on `b_feature ` like `a_feature = [b_feature]` in `A/Cargo.toml`. Only after that I can condition my compilation on `a_feature`. However my question asks if this can be avoided and if there is a way to use `b_feature` directly in code of crate `A`. – tkachuko Sep 07 '22 at 06:39
  • It is strange that the source code in `A` can be aware of the feature of `B` but cargo.toml in `A` cannot be aware. – Ömer Erden Sep 07 '22 at 06:55
  • Fair point. However at the same time this approach introduces feature flag to crate A that I do not intend to use. – tkachuko Sep 07 '22 at 15:55

1 Answers1

1

In most cases, according to doc.rust-lang/features, you are required to have a feature flag if you write #[cfg(feature = "<any_feature>")]. But to go without a "feature" flag, it can't be achieved in a normal way on the current version of rust.

If you have access to write code in your upstream crate (like Crate B in your case). The most feasible workaround is achieved by using macro in your upstream crate. See How can my crate check the selected features of a dependency?

tieway59
  • 191
  • 1
  • 5
  • I do not think that allows me to condition compilation in crate `A` on `b_feature` – tkachuko Sep 07 '22 at 06:29
  • @tkachuko Do you feel acceptable about not using `#[cfg(feature = "")]` but using two macros defined in your Crate B by condition compilation? – tieway59 Sep 07 '22 at 06:52
  • Nice, thanks! Yes, that looks like something I was looking for even though it looks a bit hacky indeed (as per original question). – tkachuko Sep 07 '22 at 15:58