Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust cfg! and compile_error!

Reference for the Rust cfg! macro and compile_error!: testing configuration at compile time, any/all/not, target checks and stopping a build with a message.

cfg!(condition) evaluates to a bool constant that says whether a configuration predicate is true for the current build, for example cfg!(debug_assertions) or cfg!(target_os = "linux"). Both branches of an if cfg!(...) are still compiled and type-checked; only the value is decided at compile time.

compile_error!("message") stops compilation with your message. It is mostly used together with the #[cfg] attribute, where it only exists when a bad configuration is selected, and inside macros to reject invalid input.

Rust
if cfg!(target_pointer_width = "64") { /* ... */ }
#[cfg(all(unix, windows))]
compile_error!("cannot be both unix and windows");

Try it

Rust Asking about the build configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust compile_error! stops the build

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
cfg!(predicate)               // bool
compile_error!("message");    // never compiles

Predicates: name (such as unix, windows, test, debug_assertions), key = "value" (such as target_os = "linux", target_arch = "x86_64", feature = "serde"), and the combinators all(...), any(...), not(...).

Name Description
predicate A configuration predicate as described above.
message A string literal shown as the compile error.

Usage notes

  • cfg! vs #[cfg]. cfg! keeps both branches in the program, so both must compile on every platform. With #[cfg(...)] the other code is removed before type checking, which is needed when it uses platform-only APIs.
  • Dead branches are optimized away because the condition is a constant.
  • compile_error! always fires when the compiler expands it. Unlike panic!, there is no run time. Put it behind a #[cfg] or a macro arm so it only appears on the bad path.
  • Features from Cargo appear as feature = "name"; a plain rustc build has none.
  • Unknown names in predicates are reported by the unexpected_cfgs lint, which catches typos.
  • cfg!(test) is true only when compiled with --test (Cargo's test harness).