Platform specific constants

I want to define a constant which will be different for each platform (windows, mac, Linux) and fail compilation with a suitable error message if compiled for any other platform.

If possible, I want to avoid any external dependencies.

1 Like

Conditional compilation:

#[cfg(target_os = "windows")]
const VALUE: usize = 0;
#[cfg(target_os = "linux")]
const VALUE: usize = 1;
#[cfg(target_os = "macos")]
const VALUE: usize = 2;
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
compile_error!("Unsupported platform.");

It's easier with the cfg_if crate:

cfg_if::cfg_if! {
    if #[cfg(target_os = "windows")] {
        const VALUE: usize = 0;
    } else if #[cfg(target_os = "linux")] {
        const VALUE: usize = 1;
    } else if #[cfg(target_os = "macos")] {
        const VALUE: usize = 2;
    } else {
        compile_error!("Unsupported platform.");
    }
}
3 Likes

Thanks for the solution. Can I use match in this case?

You could match on the numeric value:

match VALUE {
    0 => "windows",
    1 => "linux",
    2 => "mac",
    _ => panic!(),
}

but a better approach would then be to create an enum:

enum Platform {
    Windows,
    Linux,
    Mac,
}

#[cfg(target_os = "windows")]
const VALUE: Platform = Platform::Windows;
#[cfg(target_os = "linux")]
const VALUE: Platform = Platform::Linux;
#[cfg(target_os = "macos")]
const VALUE: Platform = Platform::Mac;
#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
compile_error!("Unsupported platform.");
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.