Skip to contentSkip to conversation

rust: lib: add if_cfg! macro for conditional compilation

PATCH Superseded Areej 5 participants 8 messages Aug 13, 2025 – Aug 15, 2025 1 message not in the archive Rust

lore
Share & tools
lore

Areej

author
#0 lore raw

PATCH 1/1 rust: lib: add if_cfg! macro for conditional compilation

Add a new if_cfg! macro to simplify conditional compilation using cfg attributes. This macro expands to paired #[cfg(cond)] and #[cfg(not(cond))] blocks, allowing compile-time selection between code branches in both expression and statement contexts.

---
 rust/kernel/lib.rs | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
rust/kernel/lib.rs +37 -0
index ed53169e795c..47e73949392d 100644
@@ -294,6 +294,42 @@ macro_rules! asm {
     };
 }
 
+/// Conditionally compiles and executes code based on a `#[cfg]` condition.
+///
+/// Expands to `#[cfg(cond)] { ... }` and `#[cfg(not(cond))] { ... }`,
+/// allowing conditional compilation in both expression and statement positions.
+///
+/// This macro is useful when both branches must be valid Rust code and the
+/// selection between them is done at compile time via a config option.
+/// # Examples
+/// ```
+/// # use kernel::if_cfg;
+/// // Select a value depending on CONFIG_64BIT.
+/// let x = if_cfg!(if CONFIG_64BIT {
+///     64
+/// } else {
+///     32
+/// });
+///
+/// // `x` will be 64 if CONFIG_64BIT is enabled, otherwise 32.
+/// assert!(x == 64 || x == 32);
+/// ```
+#[macro_export]
+macro_rules! if_cfg {
+    (if $cond:tt { $($then:tt)* } else { $($else:tt)* }) => {{
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { $($else)* }
+    }};
+    (if $cond:tt { $($then:tt)* }) => {{
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { () }
+    }};
+}
+
 /// Gets the C string file name of a [`Location`].
 ///
 /// If `file_with_nul()` is not available, returns a string that warns about it.
@@ -337,3 +373,4 @@ pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::f
         c"<Location::file_with_nul() not supported>"
     }
 }
+
Signature · 1 line
2.43.0
#1 lore raw
Quoted 26 lines · Areej

Add a new if_cfg! macro to simplify conditional compilation using cfg attributes. This macro expands to paired #[cfg(cond)] and #[cfg(not(cond))] blocks, allowing compile-time selection between code branches in both expression and statement contexts.

---
 rust/kernel/lib.rs | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
rust/kernel/lib.rs +6 -0
index ed53169e795c..47e73949392d 100644
@@ -294,6 +294,42 @@ macro_rules! asm {
     };
 }
 
+/// Conditionally compiles and executes code based on a `#[cfg]` condition.
+///
+/// Expands to `#[cfg(cond)] { ... }` and `#[cfg(not(cond))] { ... }`,
+/// allowing conditional compilation in both expression and statement positions.
+///
+/// This macro is useful when both branches must be valid Rust code and the

rust/kernel/lib.rs macro_rules! asm { · line 312

Quoted 10 lines
rust/kernel/lib.rs +10 -0
+/// selection between them is done at compile time via a config option.
+/// # Examples
+/// ```
+/// # use kernel::if_cfg;
+/// // Select a value depending on CONFIG_64BIT.
+/// let x = if_cfg!(if CONFIG_64BIT {
+///     64
+/// } else {
+///     32
+/// });

Isn't this the same as cfg!()?

if cfg!(CONFIG_64BIT) {
	64
} else {
	32
}

https://doc.rust-lang.org/std/macro.cfg.html

Quoted 24 lines
rust/kernel/lib.rs +20 -0
+///
+/// // `x` will be 64 if CONFIG_64BIT is enabled, otherwise 32.
+/// assert!(x == 64 || x == 32);
+/// ```
+#[macro_export]
+macro_rules! if_cfg {
+    (if $cond:tt { $($then:tt)* } else { $($else:tt)* }) => {{
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { $($else)* }
+    }};
+    (if $cond:tt { $($then:tt)* }) => {{
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { () }
+    }};
+}
+
 /// Gets the C string file name of a [`Location`].
 ///
 /// If `file_with_nul()` is not available, returns a string that warns about it.

rust/kernel/lib.rs pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::f · line 376

Quoted 4 lines
rust/kernel/lib.rs +1 -0
@@ -337,3 +373,4 @@ pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::f
         c"<Location::file_with_nul() not supported>"
     }
 }
+

Spurous whitespace change.

A message that is not in the archive (sent off-list or not yet received): CAMjM9+b60ate7cpHfm6uPHFauuYyPA1KcukqMgLjCQcC_zak+A@mail.gmail.com

#3 lore raw

Hi!

Please respond inline instead of top-posting.

Quoted 53 lines · Areej
Quoted 43 lines · Thomas Weißschuh
Quoted 17 lines · Areej

Add a new if_cfg! macro to simplify conditional compilation using cfg attributes. This macro expands to paired #[cfg(cond)] and #[cfg(not(cond))] blocks, allowing compile-time selection between code branches in both expression and statement contexts.

---
 rust/kernel/lib.rs | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
rust/kernel/lib.rs +0 -0
index ed53169e795c..47e73949392d 100644

rust/kernel/lib.rs macro_rules! asm { · line 297

Quoted 4 lines
rust/kernel/lib.rs +1 -0
@@ -294,6 +294,42 @@ macro_rules! asm {
     };
 }
 
+/// Conditionally compiles and executes code based on a `#[cfg]`

condition.

rust/kernel/lib.rs macro_rules! asm {

Quoted 3 lines
rust/kernel/lib.rs +3 -0
+///
+/// Expands to `#[cfg(cond)] { ... }` and `#[cfg(not(cond))] { ... }`,
+/// allowing conditional compilation in both expression and statement

positions.

rust/kernel/lib.rs macro_rules! asm { · line 302

Quoted 2 lines
rust/kernel/lib.rs +2 -0
+///
+/// This macro is useful when both branches must be valid Rust code and

the

rust/kernel/lib.rs macro_rules! asm { · line 312

Quoted 10 lines
rust/kernel/lib.rs +10 -0
+/// selection between them is done at compile time via a config option.
+/// # Examples
+/// ```
+/// # use kernel::if_cfg;
+/// // Select a value depending on CONFIG_64BIT.
+/// let x = if_cfg!(if CONFIG_64BIT {
+///     64
+/// } else {
+///     32
+/// });

Isn't this the same as cfg!()?

Quoted 7 lines
if cfg!(CONFIG_64BIT) {
        64
} else {
        32
}

https://doc.rust-lang.org/std/macro.cfg.html

Quoted 8 lines

The key difference is that cfg!() requires both branches to contain valid, compilable code, while if_cfg!() uses true conditional compilation via #[cfg], so only the branch that matches the configuration is compiled. This difference matters when different configurations enable/disable entire subsystems, and functions or types may only exist under certain config options. The if_cfg!() macro enables cleaner conditional compilation without compilation errors from referencing code that isn’t included in the current configuration.

The docs for if_cfg!() also says that "both branches must be valid Rust code". And the example case would be better served by cfg!(). Can both the docs and example provide a clear distinction between the two?

Quoted 35 lines
Quoted 35 lines

the

Quoted 13 lines
rust/kernel/lib.rs +13 -0
+///
+/// // `x` will be 64 if CONFIG_64BIT is enabled, otherwise 32.
+/// assert!(x == 64 || x == 32);
+/// ```
+#[macro_export]
+macro_rules! if_cfg {
+    (if $cond:tt { $($then:tt)* } else { $($else:tt)* }) => {{
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { $($else)* }
+    }};
+    (if $cond:tt { $($then:tt)* }) => {{

rust/kernel/lib.rs macro_rules! asm {

Quoted 10 lines
rust/kernel/lib.rs +7 -0
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { () }
+    }};
+}
+
 /// Gets the C string file name of a [`Location`].
 ///
 /// If `file_with_nul()` is not available, returns a string that warns

about it.

rust/kernel/lib.rs pub fn file_from_location<'a>(loc: &'a

Quoted 1 line
rust/kernel/lib.rs +0 -0
@@ -337,3 +373,4 @@ pub fn file_from_location<'a>(loc: &'a

core::panic::Location<'a>) -> &'a core::f

rust/kernel/lib.rs pub fn file_from_location<'a>(loc: &'a core::panic::Location<'a>) -> &'a core::f · line 376

Quoted 4 lines
rust/kernel/lib.rs +1 -0
         c"<Location::file_with_nul() not supported>"
     }
 }
+

Spurous whitespace change.

#4 lore raw

PATCH v2 1/1 rust: lib: add if_cfg! macro for conditional compilation

Add the if_cfg! macro to simplify conditional compilation using cfg attributes. The macro expands to paired #[cfg(cond)] and #[cfg(not(cond))] blocks, allowing compile-time selection between code branches in both expression and statement contexts.

Note: Previous documentation incorrectly stated that both branches must be valid Rust code. In reality, if_cfg!() compiles only the active branch, allowing the inactive branch to reference items that may not exist under certain configurations.

---
 rust/kernel/lib.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 51 insertions(+)
rust/kernel/lib.rs +51 -0
index ed53169e795c..6bcce24600e3 100644
@@ -294,6 +294,57 @@ macro_rules! asm {
     };
 }
 
+/// Conditionally compiles and executes code based on a `#[cfg]` condition.
+///
+/// Expands to `#[cfg(cond)] { ... }` and `#[cfg(not(cond))] { ... }`,
+/// allowing conditional compilation in both expression and statement positions.
+///
+/// # Key difference from `cfg!()`
+/// - `cfg!()` evaluates a configuration flag at compile time, but both branches must be valid Rust code
+/// - `if_cfg!()` compiles only the active branch, so the inactive branch can reference
+///   functions, types, or constants that may not exist under certain configurations
+///
+/// # Examples
+///
+/// Demonstrates the difference between `if_cfg!()` and `cfg!()`:
+/// ```ignore
+/// # use kernel::if_cfg;
+/// // FOR CONFIG_64BIT
+/// // Only the active branch is compiled - inactive branch can be invalid
+/// let x = if_cfg!(if CONFIG_64BIT {
+///     42  // valid code
+/// } else {
+///     undefined_function()  // invalid, but completely ignored by compiler
+/// });
+/// assert_eq!(x, 42);
+/// ```
+///
+/// Using `cfg!()` instead would fail compilation:
+/// ```ignore
+/// // This fails because Rust must validate both branches
+/// let x = if cfg!(CONFIG_64BIT) {
+///     42
+/// } else {
+///     undefined_function()  // compilation error - function doesn't exist
+/// };
+/// assert_eq!(x, 42);
+/// ```
+#[macro_export]
+macro_rules! if_cfg {
+    (if $cond:tt { $($then:tt)* } else { $($else:tt)* }) => {{
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { $($else)* }
+    }};
+    (if $cond:tt { $($then:tt)* }) => {{
+        #[cfg($cond)]
+        { $($then)* }
+        #[cfg(not($cond))]
+        { () }
+    }};
+}
+
 /// Gets the C string file name of a [`Location`].
 ///
 /// If `file_with_nul()` is not available, returns a string that warns about it.
Signature · 1 line
2.43.0
#5 lore raw
Quoted 2 lines · Areej Hamid

+/// # Key difference from cfg!()

Please add an empty docs line after headers. Also before opening examples below.

Quoted 1 line

+/// - cfg!() evaluates a configuration flag at compile time, but both branches must be valid Rust code

Please use intra-doc links wherever they may work. Also please end sentences with a period in docs and comments.

rust/kernel/lib.rs macro_rules! asm { · line 305

Quoted 2 lines
rust/kernel/lib.rs +2 -0
+/// - `if_cfg!()` compiles only the active branch, so the inactive branch can reference
+///   functions, types, or constants that may not exist under certain configurations

Perhaps we could say "... branch can, for instance, reference ...", or that it is not type checked in general, i.e. more things than undefined items are allowed.

Quoted 1 line

+/// // FOR CONFIG_64BIT

I would skip this line.

By the way, Tamir suggested in the linked Rust for Linux issue to match the name of the upstream one in case we want to migrate to the standard library one eventually. In the commit message, I would also mention this and link to the tracking issue that Trevor mentioned:
https://github.com/rust-lang/rust/issues/115585.

Finally, we may want to consider putting this into somewhere else, rather than the root file of the crate.

Cheers,
Miguel

#6 lore raw
Quoted 3 lines · Miguel Ojeda

Finally, we may want to consider putting this into somewhere else, rather than the root file of the crate.

By the way, there are some strange addresses in Cc: Thomas at domain dot com, Andreas at Linaro, etc.

Where are you fetching those from? Please use the ones from the MAINTAINERS file.

Thanks!

Cheers,
Miguel

reviewer
#7 lore raw
In reply to Miguel Ojeda
Quoted 5 lines · Miguel Ojeda

By the way, Tamir suggested in the linked Rust for Linux issue to match the name of the upstream one in case we want to migrate to the standard library one eventually. In the commit message, I would also mention this and link to the tracking issue that Trevor mentioned:
https://github.com/rust-lang/rust/issues/115585.

Didn't we also want to vendor the cfg-if crate? Or am I missing something?

Quoted 2 lines

Finally, we may want to consider putting this into somewhere else, rather than the root file of the crate.

Yeah, let's have it in a cfg_if.rs or whatever the macro will be called.

---
Cheers,
Benno

#8 lore raw
In reply to Areej
Quoted 4 lines · Areej

Add a new if_cfg! macro to simplify conditional compilation using cfg attributes. This macro expands to paired #[cfg(cond)] and #[cfg(not(cond))] blocks, allowing compile-time selection between code branches in both expression and statement contexts.

Nit, trailing whitespace in your text :(

Quoted 4 lines

From: line does not match up with this text :(

thanks,

greg k-h