Group global consts under #[cfg} attr

I wanted to define these in the same module as

#[cfg(target_os = "linux")]
const OS: &str = "Linux"
const OFFSET: usize = 0xa;

#[cfg(target_os = "windows")]
const OS: &str = "Windows"
const OFFSET: usize = 0x8;

However, I get an error for OFFSET refined. So, it takes only the first definition under #[cfg] attr. Is there a way to group?

As a workaround, I could do something like defining in two different modules linux.rs and windows.rs and do the below and it perfectly works, but I would like to know if there is a way to make the first option work.

#[cfg(target_os = "linux")]
use crate::linux::*;

#[cfg(target_os = "windows")]
use crate::windows::*;

You can use a macro that passes through its inputs to group the consts without creating a module.

macro_rules! group {
    ($($tt:tt)*) => { $($tt)* }
}

#[cfg(target_os = "linux")]
group! {
    const OS: &str = "Linux";
    const OFFSET: usize = 0xa;
}

#[cfg(target_os = "windows")]
group! {
    const OS: &str = "Windows";
    const OFFSET: usize = 0x8;
}

Edit: I found the post that I got this trick from.

3 Likes