2

How is it possible to access which features the package is being built with, inside the build.rs script? There is an incredibly expensive step in the script which is only needed for a particular cargo feature, but I can't see any way to access config features inside the build script.

Is there any way to read whether or not a given feature is enabled in the build.rs script?

Jason Carr
  • 194
  • 11

2 Answers2

5

I haven't been able to find documentation here, but was able to figure out one solution by guessing.

Cargo features are available as build features not just in the main source files, but inside the build.rs script as well. So you can use any of the standard ways to check configuration, like the cfg! and #[cfg(feature = "...")] macros, as mentioned in https://doc.rust-lang.org/reference/conditional-compilation.html and How do I use conditional compilation with `cfg` and Cargo?

Jason Carr
  • 194
  • 11
1

Cargo sets a number of environment variables when the build scripts are run:

https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-build-scripts

Including an environment variable for each feature:

CARGO_FEATURE_<name> — For each activated feature of the package being built, this environment variable will be present where <name> is the name of the feature uppercased and having - translated to _.

Jason Peacock
  • 1,783
  • 11
  • 17