liveBook · Manning

Conditional compilation

As explained in Write Powerful Rust Macros

Conditional compilation is the selection of source items for compilation based on compile-time configuration conditions.

Conditional compilation selects Rust source items according to compile-time configuration. Cargo features can make macros, imports, modules, and generated code optional, so users compile only the capabilities they enable. section 10.3

Apply the technique by connecting a Cargo feature to cfg attributes:

  • Enable the feature in the dependency declaration; otherwise, the guarded macro is unknown while an unguarded macro continues working. section 10.3

Feature-gated attribute macro

A library can gate `config_struct` and its `struct_output` module behind `struct`. Consumers enable it with `features = ["struct"]`, then use `#[config_struct]` on `ConfigStruct`.

How Write Powerful Rust Macros covers it

How deep it goes
Explains feature declarations, cfg placement, dependency activation, and default features, without detailing compiler configuration internals.
Examples
Uses a feature-gated config_struct macro, struct_output module, ConfigStruct consumer, and Cargo feature declarations.
What it assumes
Assumes familiarity with Rust modules, imports, procedural macros, Cargo dependencies, and attribute syntax.
What you can do after
Configure optional Rust library capabilities and verify consumer code by enabling the required Cargo feature.
How it connects
Connects Cargo features with cfg attributes, procedural macros, attribute macros, and default features.

Also explained in

Compare how 5 books explain conditional compilation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.