Search code examples
rustfltk

Depending on Build Target, use fltk::osxMenuBar or MenuBar in fltk-rs


I'm creating a cross-platform GUI App with fltk-rs. Depending on which platform I'm targeting (OSX or Windows), I'd like to use a different struct for my menu bar. If I'm targeting OSX, for my menu bar I'd like to use fltk::menu::SysMenuBar and for Windows, I'd like to use fltk::menu::MenuBar.

I don't want to keep to separate versions of my code, one for Windows, and one for OSX, just so I can use different a different Struct for my menu.

What are some approaches to changing which struct is used based on the build target without creating different codebases?

use fltk::{app::*, frame::*, image::*, window::*, menu::*};

fn main() {
    let app = App::default().with_scheme(Scheme::Gleam);
    let mut wind = Window::new(100, 100, 400, 300, "Hello from rust");
    
    //if target is Windows
    let menubar = MenuBar::default()

    //if target is OSX
    let menubar = SysMenuBar::default()

    wind.end();
    wind.show();

    app.run().unwrap();
}


Solution

  • Consulting the Rust Reference on Conditional Compilation. You would use the #[cfg(...)] attribute with the target_os option:

    #[cfg(target_os = "windows")]
    let menubar = MenuBar::default();
    
    #[cfg(target_os = "macos")]
    let menubar = SysMenuBar::default();