【问题标题】:Is glib command line parsing order-sensitive?glib 命令行解析顺序是否敏感?
【发布时间】:2015-03-21 06:04:52
【问题描述】:

glib 的命令行选项解析顺序是否敏感?在下面的代码中,我在GOptionEntry 数组中的--bar 之前定义了选项--foo。解析--foo --bar 将两者都设置为true,但--bar --foo 仅将foo 设置为true。我如何让它忽略顺序,因为无序选项是 *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;
}

结果:

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

【问题讨论】:

  • 没有使用 GOptionContext 我不能说你做错了什么......但我会挑战你的断言 *nix 选项是无序的。当它们不冲突时,显然,顺序可能无关紧要——但是当它们发生冲突时,或者当它们与其他参数混合时,顺序肯定确实很重要一些命令。

标签: c command-line-arguments glib fastq


【解决方案1】:

GOptionEntry 结构中的arg_data 指针应指向gboolean,而不是boolgbooleangint 大小相同,可能大于 bool。在您上次的测试中,settimg foo 可能会覆盖 bar

【讨论】:

  • 这正是问题所在。我真的从来没有想过,谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多