【发布时间】: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