Features in build scripts

What is the practical difference (besides the obvious one wrt what's compiled in the build script or not) between using #[cfg(feature="foo")] and std::env::var("CARGO_FEATURE_FOO") in build scripts? Are there different use cases for each? I kind of remember the latter being preferred, but I'm not sure anymore, and I can't think of a practical difference that would make it preferable.

The code annotated by #[cfg(...)] will only be present when that feature is active, while the std::env::var(...) version just changes your runtime logic.

It depends on your actual use-case, but sometimes your build script might need access to a dependency which is only included when a specific feature is enabled. In which case, you can only go with the #[cfg(...)] version. If you were to use the if std::env::var(...) version in that case, your build script would fail to compile with a "dependency not found" error.

My normal recommendation is to go with the environment variable version. Everyone knows how if-statements work and can reason about them easily, while conditional compilation can sometimes have an impact on readability.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.