Search code examples
rustcargo-features

Rust passing features to dependency


I have a system with three layers. The lowermost layer is an external C library, then I have created a wrapper library and finally a pure rust library on top. I build the C library with a build.rs script in the wrapper library. The C library is built with cmake and must be configured with -DFEATURE1=ON and -DFEATURE2=ON commandline switches.

I have configured rust features feature1 and feature2 in the Cargo.toml file of the wrapper library:

wrapper/Cargo.toml:

[features]
feature1=[]
feature2=[]
...

and in build.rs I use the cfg!() macro to pass the correct options to cmake:

use cmake::Config;
...
let mut config = Config::new("");
if !cfg(feature1) {
    config.define("FEATURE1", "ON");
}

When I build the wrapper library I can pass the correct features to the build step with:

bash% cargo build --features=feature1

and the wrapper library and the underlying C library are correctly built. But when I try to initiate the build from the pure rust library it seems the feature requests are not passed correctly down to the wrapper library:

rustlib/Cargo.toml

[dependencies.wrapper]
path="wrapper"
features=["feature1"]
...

have also tried with the commandline alternative:

bash% cargo build --features=wrapper/feature1

In both cases the end result is that the feature request does not reach the final C library.


Solution

  • Build scripts do not have the features enabled as cfg as far as I know. I don't know why it works when you invoke cargo build on the package directly.

    To inspect enabled features in build scripts, check the existence of the environment variable CARGO_FEATURE_<name>.