Macros & Metaprogramming · 16 min · free lesson

cfg & Features

cfg decides which code is compiled at all.

Core idea

#[cfg(...)] excludes selected code before name and type checking, but source syntax still has to parse. Disabling default features on one dependency edge does not prohibit another edge from enabling them.

A cfg gate includes a feature module in one build and omits it in another.
Conditional compilation changes which code enters a build.

Understand it

#[cfg(...)] removes selected code before name and type checking, so platform-specific names need not resolve on other targets. Its source must still have valid Rust syntax. Cargo features are the same mechanism driven from the manifest, which is how one crate serves both a no_std embedded user and a full desktop one.

Conditional compilation decides which items exist in a particular build. A #[cfg(target_os = "wasi")] function is present only for matching targets; the opposite branch is present elsewhere. Cargo features are named inputs to this selection, often supplied by downstream users. Because a disabled branch is not part of the resulting item set, its behavior is not a runtime toggle and it must be checked in a build where it is enabled. Test the supported feature combinations rather than assuming the default build covers them.

Features in a dependency graph are generally additive: if two dependents enable different features of the same package, Cargo can compile that package with their union. Design features so enabling an extra capability does not silently remove another. For mutually exclusive choices, use explicit compile errors or separate types/configuration instead of pretending feature flags are exclusive switches. A no_std library might gate an allocation-backed helper behind a feature, but its core API must still compile without it. Run cargo check --no-default-features and a feature-enabled build for that design. Document what each feature changes, which target constraints it carries, and whether it affects public API. If callers need to choose at runtime, use a value or trait object instead of cfg.

Remember that code behind a disabled cfg may go untested for months. Put each supported target or feature combination into a build matrix that you can run locally or in release preparation. If a feature changes public types, document the resulting API surface for downstream crates. Do not use mutually exclusive features as a substitute for a real runtime configuration choice.

Read the code

#[cfg(target_os = "wasi")]
fn platform() -> &'static str { "wasi" }
#[cfg(not(target_os = "wasi"))]
fn platform() -> &'static str { "native" }

#[cfg(feature = "extras")]
fn extra() -> u32 { 7 }

fn main() {
    println!("{}", platform());
    #[cfg(feature = "extras")]
    println!("{}", extra());
}

Matching cfg predicates select the platform implementation; enabling extras adds a second print. Every branch retains valid Rust syntax.

Practice starter

[features]
default = ["std"]
std = []

[dependencies]
memchr = { version = "2", default-features = false }

Practise this code in Playground ↗

Try it

Gate a function on a target predicate and on a feature.

What success looks like: The other branch is absent from the build, not merely unused.

Check your understanding

What does default-features = false request on that memchr declaration?

Reveal the answer
  1. Disable the dependency completely
  2. Do not request its default feature set on this edge; other dependency edges can still enable it
  3. Prohibit every feature throughout the entire dependency graph

Feature requests are unified for a package where Cargo resolves them together. This declaration omits defaults; it is not a graph-wide prohibition of std or of another named feature.

Go deeper

Common misconception: “default-features = false turns that dependency's default features off for the whole build.”

default-features = false only omits the default request on this edge. Another dependency edge can still enable them, because Cargo unifies feature requests rather than prohibiting any.

  1. Select a platform: target_os = "wasi" is false on a native build, so the first platform is removed and only the not(...) version remains.
  2. Check the feature: extra and its println! carry feature = "extras". Without that feature both are absent, so extra is not unused; it does not exist.
  3. Compare the builds: A plain native build prints native. With --features extras it also prints 7, from a different set of compiled items.

Transfer challenge: Remove #[cfg(feature = "extras")] from the println! in main. Predict which build fails, the plain one or --features extras, then check both.

Connections

  • Procedural Macros: Derive, attribute, and function macros
  • unsafe Rust: Five powers and their invariants
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: cfg & Features (courseId "systems", lessonId "cfg-features")
Link: https://crabrix.com/learn/systems/cfg-features/
Goal: #[cfg(...)] excludes selected code before name and type checking, but source syntax still has to parse. Disabling default features on one dependency edge does not prohibit another edge from enabling them.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=systems/cfg-features) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.