这个例子是glib帮助文档上的,
我只是加了一个hook的调用和几个打印函数,以及一些注释。
以便更好理解这个程序。
#include <gtk/gtk.h>
#define GETTEXT_PACKAGE "test"
#define ENTRIES 5
#include <glib/gi18n.h>
static gint repeats = 2;
static gint max_size = 8;
static gboolean verbose = FALSE;
static gboolean beep = FALSE;
static gboolean rando = FALSE;
static GOptionEntry entries[] =
{
// long_name, short_name, flags, arg, arg_data, description, description_data
{ "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 },
{ "rando", 0, 0, G_OPTION_ARG_NONE, &rando, "Randomize the data", NULL },
{ NULL }
};
// show all input args
void dumpArgs(int argc, char *argv[]) {
int i;
for (i = 0; i < argc; i++) {
g_print ("args %d: %s\n", i, argv[i]);
}
g_print ("\n");
}
// show all updated variables
static inline void dumpVars() {
int i;
g_print ("\n");
g_print ("repeats: %d\n", repeats);
g_print ("max-size: %d\n", max_size);
g_print("beep: %s\n", beep?"true":"false");
g_print ("verbose: %s\n", verbose?"true":"false");
g_print ("rando: %s\n", rando?"true":"false");
}
static gboolean
parse_pre (GOptionContext * context, GOptionGroup * group, gpointer data,
GError ** error)
{
g_print("Enter parse_pre, called before parse");
return TRUE;
}
static gboolean
parse_post (GOptionContext * context, GOptionGroup * group, gpointer data,
GError ** error) {
g_print("Enter parse_post, called after parse. ");
return TRUE;
}
int
main (int argc, char *argv[])
{
GError *error = NULL;
GOptionContext *context;
context = g_option_context_new ("- test tree model performance");
g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
GOptionGroup *group = gtk_get_option_group (TRUE);
g_option_context_add_group (context, group);
g_print ("input arg vector:\n");
dumpArgs(argc, argv);
// set hook function. i, we always start to work at parse_post function
g_option_group_set_parse_hooks (group, (GOptionParseFunc) parse_pre,
(GOptionParseFunc) parse_post);
if (!g_option_context_parse (context, &argc, &argv, &error))
{
g_print ("option parsing failed: %s\n", error->message);
exit (1);
}
// at here, variables had already been updated by g_option_context_parse.
g_print ("parsed arg vector:\n");
dumpArgs(argc, argv);
g_print ("updated variables:\n");
dumpVars();
/* ... */
}