Program outputs `Unknown option` even though arguments are parsed

I am creating an application using Rust + GTK4 + libadwaita and currently in the process of creating some launcher arguments using std::env::args(), testing it using an argument --trace. When I build and run my project (compile resources and then cargo run -- --trace), the program fails with Unknown option --trace. Here is my code for the argument parsing:

use simple_logger::SimpleLogger;

fn main() {
    let args = std::env::args().skip(1);
    for arg in args {
        match arg.as_str() {
            "--trace" => {
                println!("Starting log at trace level");
                SimpleLogger::new().init().unwrap();
            }
            _ => {
                eprintln!("Unknown argument {arg}");
                std::process::exit(1);
            }
        }
    }

    adw::init().expect("Failed to initialize libadwaita");
    gtk::init().expect("Failed to initialize GTK4");

    // ... initialize the app
}

Any responses is helpful because I have no clue why this is happening.

gtk::init() will parse command line arguments again.

unfortunately, the gtk crate doesn't expose an API to initialize gtk with user provided argv, and rust doesn't have API to modify the process environment block, so you'll have to initialize gtk yourself using the raw ffi binding and tell gtk when done.

relative API:

2 Likes

Thanks for the reply. That was indeed the problem. Since I used adw::Application, I just skipped GTK initialization altogether and passed unneeded arguments to Application::run_with_args() for the program to work.