Use feature of crate dependency without its declaration in toml

Viewed 76

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"]
1 Answers

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?

Related