4

I can't compile that code under ubuntu 11.10 while it compiles normally under ubuntu 10.04:

#include <stdio.h>
#include <glib.h>
int main(int argc, char** argv) {
     GList* list = NULL;
     list = g_list_append(list, "Hello world!");
     printf("The first item is '%s'\n", g_list_first(list)->data);
     return 0;
}

$ gcc $(pkg-config --cflags --libs glib-2.0) hello_glib.c

hello_glib.c:(.text+0x24): undefined reference to g_list_append
hello_glib.c:(.text+0x34): undefined reference to g_list_first
collect2: ld returned 1 exit status

I have the libglib2.0-dev installed, why the error then ?

Jorge Castro
  • 71,754

1 Answers1

6

Try this, I think the libs have to go after "hello_glib.c":

gcc -Wall -o hello_glib hello_glib.c $(pkg-config --cflags --libs glib-2.0)
./hello_glib

Don't ask me why, I don't know, but the order seems to be required, it was used in a recent (unrelated) patch: http://bazaar.launchpad.net/~ubuntu-branches/ubuntu/oneiric/getstream/oneiric/revision/7#debian/patches/as-needed.dpatch

You also had another error:

test.c: In function ‘main’: test.c:6:6: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘gpointer’ [-Wformat]

I'm not a C expert, but I think you should convert the list data to a character string:

#include <stdio.h>
#include <glib.h>
int main(int argc, char** argv) {
     GList* list = NULL;
     list = g_list_append(list, "Hello world!");
     char* str = g_list_first(list)->data;
     printf("The first item is '%s'\n", str);
     return 0;
}

Happy holidays. :)