2014-01-16 18 views
1

glib的命令行選項解析順序是否敏感?在下面的代碼中,我在GOptionEntry陣列中的--bar之前定義了選項--foo。解析--foo --bar將這兩個都設置爲true,但--bar --foo只有foo爲true。我如何讓它無視秩序,因爲無序的選項是* nix afaik中的常態。glib命令行解析是否順序敏感?

#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; 
} 

結果:

> ./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 
+0

沒有使用GOptionContext我不能說你做錯了什麼......但我會質疑你的斷言,即* nix選項是無序的。當他們不_conflict_時,顯然,順序可能並不重要 - 但是當他們這樣做,或者當他們與其他參數混合在一起時,爲了某些命令明確命令_does_很重要。 – keshlam

回答

3

arg_data指針在GOptionEntry結構應指向gboolean,而不是一個bool。 A gbooleangint大小相同,可能大於bool。在最後的測試中,settimg foo可能會覆蓋bar

+0

這正是問題所在。我真的不會想到它,謝謝。 – user3243135