Feature doesn't work in dependencies

I wrote a small library itconfig and i wanted to separate new feature, but it doesn't work when we declare this feature in Cargo.toml dependecies.

In library i have code:

#[cfg(feature = "static")]
pub extern crate lazy_static;
    
// ... in another file
    

#[macro_export]
#[doc(hidden)]
macro_rules! __itconfig_parse_variables {
    ...
    // Find static concatenated variable
    (
         ...
    ) => {
        #[cfg(feature = "static")]
        __itconfig_parse_variables! { ... }

        #[cfg(not(feature = "static"))]
        __itconfig_invalid_syntax!(feature "static");
    };

In Cargo.toml i write
itconfig = { path = "../../itconfig", features = ["static"] }

And it doesn't work!
But if we use new feature in another package we can add feature to itconfig package

[features]
default = ["static"] # without sub feature doesn't work
static = ["itconfig/static"]

rustc --version
rustc 1.41.0 (5e1a79984 2020-01-27)

Possibly related? Proc macro crates not given transitive features when they are enabled by other crates in the workspace · Issue #7833 · rust-lang/cargo · GitHub

I have the same problem in the project without workspace.

With structure:

  • src
  • Cargo.toml

In Cargo.toml I want to use

itconfig = { version = "0.11", features = ["static"] }

but only this works

[features]
default = ["static"]
static = ["itconfig/static"]

The problem might be that the #[cfg(feature = "static")] will be output by the macro into your downstream crate, instead of testing the feature from itconfig.

You can fix this by delegating to another macro, which changes its definition based on the feature

macro_rules! __itconfig_parse_variables {
    (...) => {
        $crate::__itconfig_parse_variables_inner!(...);
    };
}

#[cfg(feature = "static")]
macro_rules! __itconfig_parse_variables_inner {
    (...) => {
        $crate::__itconfig_parse_variables! { ... }
    };
}

#[cfg(not(feature = "static"))]
macro_rules! __itconfig_parse_variables_inner {
    (...) => {
        $crate::__itconfig_invalid_syntaxt!(feature "static");
    };
}

(though given it's already another macro-call, you may be able to simplify this somewhat for your specific case).

2 Likes

Thank you so much! Your solution is great. I understood where a mistake was... macros added feature condition to another package where this macros was called.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.