尝试从GArray中检索GHashTable时未定义GHashTable

时间:2017-12-26 05:01:42

标签: c gcc glibc glib

编译器说GHashTable没有定义,但很明显,如果我在从数组中检索GHashTables的代码上面使用它,它就被定义了。到底是怎么回事?我很困惑。

gcc -Wall -o tht `pkg-config --cflags glib-2.0` TestGLib.c `pkg-config --libs glib-2.0`
In file included from /usr/include/glib-2.0/glib.h:31:0,
                 from TestGLib.c:5:
TestGLib.c: In function ‘main’:
/usr/include/glib-2.0/glib/garray.h:67:62: error: invalid use of undefined type ‘struct _GHashTable’
 #define g_array_index(a,t,i)      (((t*) (void *) (a)->data) [(i)])
                                                              ^
TestGLib.c:24:34: note: in expansion of macro ‘g_array_index’
         GHashTable *current_ht = g_array_index(g_arr_hts, GHashTable, i);
                                  ^~~~~~~~~~~~~
/usr/include/glib-2.0/glib/garray.h:67:62: error: dereferencing pointer to incomplete type ‘GHashTable {aka struct _GHashTable}’
 #define g_array_index(a,t,i)      (((t*) (void *) (a)->data) [(i)])
                                                              ^
TestGLib.c:24:34: note: in expansion of macro ‘g_array_index’
         GHashTable *current_ht = g_array_index(g_arr_hts, GHashTable, i);
                                  ^~~~~~~~~~~~~
TestGLib.c:26:22: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
         printf("%s", (gchar) g_hash_table_lookup(current_ht, "key"));
                      ^
TestGLib.c:26:18: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]
         printf("%s", (gchar) g_hash_table_lookup(current_ht, "key"));
                 ~^   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                 %d

我试图编译的代码非常简单。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <glib.h>

int main() {

    GHashTable *g_ht_first = g_hash_table_new_full(g_str_hash, g_str_equal, free, free);
    g_hash_table_insert(g_ht_first, g_strdup("key"), g_strdup("val"));

    GHashTable *g_ht_second = g_hash_table_new_full(g_str_hash, g_str_equal, free, free);
    g_hash_table_insert(g_ht_second, g_strdup("key"), g_strdup("val"));

    GArray *g_arr_hts = g_array_new(FALSE, FALSE, 2);

    g_array_append_val(g_arr_hts, g_ht_first);
    g_array_append_val(g_arr_hts, g_ht_second);

    int i;

    for (i = 0; i < g_arr_hts->len; i++) {

        GHashTable *current_ht = g_array_index(g_arr_hts, GHashTable, i);

        printf("%s", (gchar) g_hash_table_lookup(current_ht, "key"));

    }

    return 0;
}

由于

1 个答案:

答案 0 :(得分:0)

好的,回到文档之后,我注意到Glib也有Pointer Array GPtrArray,所以我更新了我的代码并且它有效。不知道常规GArray不支持指针。 :)

https://developer.gnome.org/glib/stable/glib-Pointer-Arrays.html