liveBook · Manning

Conditional compilation

As explained in Code Like a Pro in Rust

A cfg attribute is a Rust compiler attribute that conditionally includes or excludes the attached source item according to configuration predicates.

Conditional compilation selects Rust code or attributes according to configuration predicates. Use it to support optional Cargo features and platform-specific implementations without including every implementation in every build. section 2.3 section 5.8.2

Choose the tool according to what must be conditional:

  • `#[cfg(predicate)]` includes the attached code only when the predicate is true. section 2.3 section 5.8.2
  • `#[cfg_attr(predicate, attribute)]` applies an attribute only when the predicate is true. section 2.3
  • `cfg!(predicate)` evaluates to a compile-time boolean; for example, `cfg!(target_feature = "avx2")` tests whether the target feature is enabled. section 5.8.2
  • Combine predicates with `not`, `all`, and `any` to express exclusions or multiple conditions. section 2.3

For an optional `serde` feature, gate the import with `cfg` and use `cfg_attr` to select derives. The non-`serde` configuration retains the other derives without requiring serialization support. section 2.3

Listing 2.3 Partial code for src/message.rs from the dryoc crate
#[cfg(feature = "serde")]                                                #1
use serde::{Deserialize, Serialize};
 
use zeroize::Zeroize;
 
#[cfg_attr(                                                              #2
    feature = "serde",                                                   #2
    derive(Serialize, Deserialize, Zeroize, Debug, PartialEq)            #2
)] 
#[cfg_attr(not(feature = "serde"), derive(Zeroize, Debug, PartialEq))]   #3
#[zeroize(drop)]
/// Message container, for use with unencrypted messages
pub struct Message(pub Box<InputBase>);

Inspect the feature-gated import and complementary derive attributes on `Message`. section 2.3

Platform predicates can select implementations at the statement level. In a protected-memory allocator, `#[cfg(unix)]` selects a `posix_memalign` path, while `#[cfg(windows)]` selects a `VirtualAlloc` path. section 5.8.2

Listing 5.13 Partial code listing for allocate() from page-aligned allocator
fn allocate(&self, layout: Layout,
) -> Result<ptr::NonNull<[u8]>, AllocError> {
    let pagesize = *PAGESIZE;
    let size = _page_round(layout.size(), pagesize) + 2 * pagesize;     #1
    #[cfg(unix)]
    let out = {
        let mut out = ptr::null_mut();
        let ret = unsafe {
            libc::posix_memalign(&mut out, pagesize as usize, size)     #2
        };
        if ret != 0 {
            return Err(AllocError);
        }
        out
    };
    #[cfg(windows)]
    let out = {
        use winapi::um::winnt::{MEM_COMMIT, MEM_RESERVE, PAGE_READWRITE};
        unsafe {
            winapi::um::memoryapi::VirtualAlloc(                        #3
                ptr::null_mut(), size, MEM_COMMIT | MEM_RESERVE,
                PAGE_READWRITE,
            )
        }
    };
    let fore_protected_region = unsafe {
        std::slice::from_raw_parts_mut(out as *mut u8, pagesize)
    };
    mprotect_noaccess(fore_protected_region)                           #4
        .map_err(|err| {
            eprintln!("mprotect error = {:?}, in allocator", err)
        })
        .ok();
    let aft_protected_region_offset =
        pagesize + _page_round(layout.size(), pagesize);
    let aft_protected_region = unsafe {
        std::slice::from_raw_parts_mut(
            out.add(aft_protected_region_offset) as *mut u8,
            pagesize,
        )
    };
    mprotect_noaccess(aft_protected_region)                            #5
        .map_err(|err| {
            eprintln!("mprotect error = {:?}, in allocator", err)
        })
        .ok();
    let slice = unsafe {
        std::slice::from_raw_parts_mut(
            out.add(pagesize) as *mut u8,
            layout.size(),
        )
    };
    mprotect_readwrite(slice)                                          #6
        .map_err(|err| {
            eprintln!("mprotect error = {:?}, in allocator", err)
        })
        .ok();
    unsafe { Ok(ptr::NonNull::new_unchecked(slice)) }                  #7
}

Compare the Unix and Windows allocation paths in the partial allocator implementation. section 5.8.2

Keep feature combinations manageable. If a crate accumulates many feature flags, consider splitting it into smaller subcrates; some optional behavior, such as top-level trait implementations, may still require flags. section 2.3

How Code Like a Pro in Rust covers it

How deep it goes
Explains attribute scope, conditional attributes, boolean configuration tests, and predicate composition through implementation snippets.
Examples
Uses serde-gated imports and derives, Unix and Windows allocator paths, and an avx2 target-feature test.
What you can do after
Apply conditional compilation with Rust's cfg and cfg_attr attributes and cfg! macro to feature- and platform-specific code.
How it connects
Connects Cargo feature flags, optional dependencies, target features, and platform-specific memory allocation.

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