Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional compilation: #[cfg(foo)] vs #[cfg(feature = "foo")]

Tags:

rust

AFAIK, #[cfg(foo)] can be activated with rustc --cfg foo or with rustflags = "--cfg foo" in .cargo/config.toml

and #[cfg(feature="foo")] is enabled with cargo build -F foo

Both seem to achieve conditional compilation, but which one is the correct method?

like image 829
exlinx Avatar asked Oct 15 '25 02:10

exlinx


1 Answers

You'll most likely want to use features. They can be turned on and off on a per crate basis. That also means that dependants can disable parts of your code that they don't need using features, which is how a lot of features work.

Take axum as an example, which hides something like Cookies behind a cookies feature, since not every project that uses axum will want or need to use cookies.

The --cfg rustflag on the other hand is more useful if you want to enable or disable code for an entire workspace (or project) and don't really plan on disabling these on a per crate basis. I have most often seen these flags used by projects that have custom build systems (for example AeroOS, which uses the --cfg flag to enable or disable 5-Level paging).

Also see @Masklinn comment

like image 68
IcyTv Avatar answered Oct 17 '25 20:10

IcyTv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!