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;
}
3.編譯
# 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
4.run測試
# ./test -h
Usage:
test [OPTION?] - test tree model performance
This is a glib demo
Help Options:
-h, --help Show help options
Application Options:
-s, --long name=arg_description description
-r, --repeats=N Average over N repetitions
-m, --max-size=M Test up to 2^M items
-v, --verbose Be verbose
-b, --beep Beep when done
--rand Randomize the data
# ./test -r 66 -m 6
Now value is: repeats=66, max_size=6, verbose=0, beep=0
5.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;
Linux glib命令行解析GOptionEntry使用
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.