0

Is it possible to conditionally include an [[example]]? I have an example which only runs on *nix, so it causes errors on windows.

I'm trying to avoid writing #[cfg(not(target_family = "windows"))] on every single top-level item in main.rs, and I also don't want to compromise the code structure (introducing extra modules) or mess up IDE integration ideally.


Changing [[example]] to [[target.'cfg(not(target_family = "windows"))'.example]] (in Cargo.toml) did not work.


Adding #![cfg(not(target_family = "windows"))] to the top of the file causes:

main function not found in crate my_example

Adding #![cfg_attr(target_family = "windows", crate_type = "lib")] does not get around this as:

crate_type within an #![cfg_attr] attribute is deprecated


Also tried using a declarative macro, but it doesn't actually work (seems item doesn't match modules), and isn't ideal even if it did work as it messes with IDE assistance.

macro_rules! no_windows {
    (
        $( x:item )*
    ) => {
        $(
            #[cfg(not(target_family = "windows"))]
            $x
        )*

        #[cfg(target_family = "windows")]
        fn main() {
            unimplemented!();
        }
    };
}

no_windows! {

// normal code here

}
Mingwei Samuel
  • 2,917
  • 1
  • 30
  • 40

1 Answers1

0

There might be a better way, but something like this should work

#[cfg(not(target_family = "windows"))]
mod non_windows {
    // ...
    
    pub fn main() {
        // ...
    }
}

fn main() {
    #[cfg(not(target_family = "windows"))]
    non_windows::main();
}
PitaJ
  • 12,969
  • 6
  • 36
  • 55