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

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;
}


谢谢

最佳答案

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

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

关于c - 尝试从GArray检索GHashTable时未定义,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47974045/

10-09 13:31