liveBook · Manning

Conditional compilation

As explained in Learn Rust in a Month of Lunches

A conditional compilation attribute instructs the Rust compiler to include or exclude an item according to a configuration condition.

Conditional compilation uses Rust’s cfg attribute to include or exclude an item according to a configuration condition. The condition can describe testing or a target operating system. section 13.1.5

Common uses include:

  • Place #[cfg(test)] above test code so it is compiled only while testing. section 13.1.5 section 14.2.3
  • Place #[cfg(target_os = "windows")] above code intended only for Windows; equivalent conditions can target Linux or other systems. section 13.1.5
  • Combine #[cfg(test)] with a module to keep several tests together while excluding the whole module outside testing. section 14.2.3

A test-only module

A usual pattern places #[cfg(test)] above a tests module, imports surrounding items with use super::*, and keeps #[test] above each test function. The module is omitted when the program is not being tested. section 14.2.3

fn return_two() -> i8 {
    2
}
fn return_six() -> i8 {
    4 + return_two()
}
 
#[cfg(test)]
mod tests {
    use super::*;
 
    #[test]
    fn it_returns_six() {
        assert_eq!(return_six(), 6)
    }
    #[test]
    fn it_returns_two() {
        assert_eq!(return_two(), 2);
    }
}

Inspect the complete example showing cfg(test), a test module, use super::*, and two test functions. section 14.2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains attribute syntax and test-module organization with examples, but does not develop a broader condition grammar.
Examples
Shows #[cfg(test)], #[cfg(target_os = "windows")], and a conditional tests module containing assert-based tests.
What it assumes
Assumes basic Rust functions and modules while introducing configuration attributes through focused testing examples.
What you can do after
Apply it via Rust’s cfg attribute to organize test-only and operating-system-specific code.
How it connects
Connects conditional compilation with attributes, modules, testing, and target operating systems.

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 Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.