最近发现了一个好东东,glib 库中的 GOptionEntry,用于解析应用程序的命令行参数
实验环境:win10 + 虚拟机 + Ubuntu18.04.2
1 安装glib
# 安装依赖库
sudo apt-get install libffi-dev -y
# 安装glib
sudo apt-get install libglib2.0-dev -y
# 64位ubuntu安装32位glib2.0, 仅作参考
sudo apt-get install libglib2.0-dev:i386
2 实例
话不多说,先上个栗子:
// test.c
#include <glib.h>
#include <locale.h>
#define ERR_MSG_V(msg, ...) \
g_print("** ERROR: <%s:%d>: " msg "\n", __func__, __LINE__, ##__VA_ARGS__)
static gint repeats = 2;
static gint max_size = 8;
static gboolean verbose = FALSE;
static gboolean beep = FALSE;
static gboolean op_rand = FALSE;
static gchar arg_data[32] = { "arg data" };
static GOptionEntry entries[] =
{
{"long name" , 's' /*short-name*/ , 0 /*flags*/ , G_OPTION_ARG_STRING /*arg*/ ,
arg_data, "description" , "arg_description" },
{"repeats" , 'r' , 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions" , "N" },
{"max-size" , 'm' , 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items" , "M" },
{"verbose" , 'v' , 0, G_OPTION_ARG_NONE, &verbose, "Be verbose" , NULL},
{"beep" , 'b' , 0, G_OPTION_ARG_NONE, &beep, "Beep when done" , NULL},
{"rand" , 0, 0, G_OPTION_ARG_NONE, &op_rand, "Randomize the data" , NULL},
{NULL}
};
int main (int argc, char *argv[])
{
GError *error = NULL;
GOptionContext *context = NULL;
GOptionGroup *group = NULL;
// 创建一个新的选项上下文
context = g_option_context_new("- test tree model performance" );
#if 1
// 如果主要组不存在则创建主要组,向组添加entries并设置转换域
g_option_context_add_main_entries(context, entries, NULL);
//添加要在选项列表之前的--help输出中显示的字符串。 这通常是程序功能的摘要
g_option_context_set_summary(context, "This is a glib demo" );
#else
group = g_option_group_new ("abc", NULL, NULL, NULL, NULL);
g_option_group_add_entries (group, entries);
g_option_context_set_main_group (context, group);
// g_option_context_add_group(context, gtk_get_option_group(TRUE));
#endif
// 解析命令行参数,识别已添加到上下文的选项
if (!g_option_context_parse(context, &argc, &argv, &error))
{
ERR_MSG_V("%s", error->message);
exit (1);
}
// 释放被解析的参数
g_option_context_free(context);
g_print("Now value is: repeats=%d, max_size=%d, verbose=%d, beep=%d\n",
repeats, max_size, verbose, beep);
return 0;
}
编译:
gcc test.c -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include \
-L/usr/lib/x86_64-linux-gnu -lglib-2.0 -o test
运行结果输出如下:
-v
-b
后面不能跟参数,因为这个参数类型为:G_OPTION_ARG_NONE
。存储它的变量是一个bool型的值,当有这个参数的值,这个bool值是TRUE,否则是FALSE。
这样当执行完g_option_context_parse
函数之后,就会发现repeats、max_size里面都有值了。
注意的是,如果参数类型为:G_OPTION_ARG_STRING
,其参数,在使用完了,需要自己来释放,否则的话就会有内存泄露。
GOptionEntry 的定义:
typedef struct GOptionEntry {
const gchar *long_name; // 参数的完整名
gchar short_name; // 简写名
gint flags; // 参数选项标准,如果不关心可直接赋0
GOptionArg arg; // 参数类型,int,string...
gpointer arg_data; // 默 认参数值
const gchar *description; // 参数意义说明
const gchar *arg_description; // 参数占位符说明
}GOptionEntry;