liveBook · Manning

Conditional compilation

As explained in Refactoring to Rust

The cfg attribute macro conditionally includes or excludes an annotated Rust item based on compile-time configuration.

Conditional compilation uses Rust’s cfg attribute macro to compile or skip an item under a particular configuration. It can select OS-specific functions, include optional crate features, or keep test code out of production builds. section 7.1 section 6.3

Attach cfg to different kinds of Rust items:

  • Use #[cfg(test)] on a module so its contents compile only during test builds. section 7.1
  • Apply cfg to functions, structs, traits, blocks, or modules. section 7.1
  • Use Cargo features to enable alternate code paths, additional dependencies, or dependency features. section 6.3
  • Create custom conditional compilation flags when users need to include or exclude whole features. section 7.1

Keeping tests out of production builds

Place unit tests in a nearby module marked #[cfg(test)]: #[cfg(test)] mod tests { #[test] fn it_works() { let result = 2 + 2; assert_eq!(result, 4); } } Cargo compiles, discovers, and runs this module with cargo test. Ordinary library or executable builds omit the module, reducing production code and avoiding accidental use of test-only values or functions. section 7.1 section 7.3

Listing 7.1 Contents of a newly initialized Rust library
#[cfg(test)]
mod tests {
  #[test]
  fn it_works() {
    let result = 2 + 2;
    assert_eq!(result, 4);
  }
}

Inspect the complete initialized Rust test module, including cfg(test), #[test], and an assertion. section 7.1

How Refactoring to Rust covers it

How deep it goes
Explains attribute placement and test-build behavior, but does not detail custom-flag configuration syntax.
Examples
Demonstrates #[cfg(test)] around a test module and features enabling Serde derive code.
What it assumes
Assumes basic Rust items, modules, attributes, and Cargo workflows while introducing conditional compilation through testing.
What you can do after
Apply via Cargo and cfg attributes to exclude tests, select platform implementations, or enable optional dependency features.
How it connects
Connects conditional compilation with Rust attributes, modules, unit testing, Cargo features, and platform-specific code.

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 Refactoring to Rust. The section links point to the parts of the book it draws on.