Question

Is glib's command line option parsing order sensitive? In the code below, I define option --foo before --bar in the GOptionEntry array. parsing --foo --bar sets both to true, but with --bar --foo only foo to true. How do I make it disregard order, since unordered options are the norm in *nix afaik.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <glib.h>

static bool foo = false;
static bool bar = false;

static GOptionEntry entries[] =
{
  { "foo" , 0 , 0 , G_OPTION_ARG_NONE , &foo , "foo" , NULL } ,
  { "bar" , 0 , 0 , G_OPTION_ARG_NONE , &bar , "bar" , NULL } ,
  { NULL }
};

int main(int argc, char * argv[]) {
    GError * error = NULL;
    GOptionContext * context = g_option_context_new ("- convert fastq");
    g_option_context_add_main_entries (context, entries, NULL);

    if (!g_option_context_parse (context, &argc, &argv, &error)){
        exit(1);
    }

    printf("%s\n", foo ? "foo is true" : "foo is false");
    printf("%d\n", bar ? "bar is true" : "bar is false");
    return 0;
}

Results:

> ./test2 
foo is false
bar is false
> ./test2 --foo
foo is true
bar is false
> ./test2 --foo --bar
foo is true
bar is true
> ./test2 --bar
foo is false
bar is true
> ./test2 --bar --foo
foo is true
bar is false
Was it helpful?

Solution

The arg_data pointer in theGOptionEntry struct should point to a gboolean, not a bool. A gboolean is the same size as a gint, which is probably larger than a bool. In your last test, settimg foo probably overwrites bar.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top