Search code examples
glib

Met undefined reference when use glib in ubuntu


I've searched about this a lot. And tried a lot. Just don't know where I go wrong.

Here is my code, it's very simple:

#include <glib.h>
int main()
{
    int *ip=g_new(int,1);
    *ip=42;
    return *ip;
}

First I try apt-get libglib2.0-dev in my Ubuntu and Mint, when it's done, compile with:

gcc `pkg-config --cflags --libs glib-2.0` -o main main.c
/tmp/ccYFljQD.o: In function `main':
main.c:(.text+0x13): undefined reference to `g_malloc_n'
collect2: error: ld returned 1 exit status
Makefile:3: recipe for target 'all' failed
make: *** [all] Error 1

And the output of pkg-config:

$ pkg-config --cflags --libs glib-2.0
-I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -lglib-2.0

So it's not working, then I try to compile from source and install one by my own. I've apt-get libffi-dev, autogen and configure, make, make install, that's all okay.

$ pkg-config --cflags --libs glib-2.0
-I/home/donpope/software/include/glib-2.0 -I/home/donpope/software/lib/glib-2.0/include -L/home/donpope/software/lib -lglib-2.0

Yet compile with the same error:

gcc `pkg-config --cflags --libs glib-2.0` -o main main.c
/tmp/cctR3iEq.o: In function `main':
main.c:(.text+0x13): undefined reference to `g_malloc_n'
collect2: error: ld returned 1 exit status
Makefile:3: recipe for target 'all' failed
make: *** [all] Error 1

So I need some help here. Thank you!

Update: Later I try this in a RedHat with older gcc. And it's just okay.


Solution

  • I have this Makefile in my glib sandbox:

    PKGS=glib-2.0
    CFLAGS+=$(shell pkg-config --cflags $(PKGS))
    LDFLAGS+=$(shell pkg-config --libs $(PKGS))
    
    %: %.c
        $(CC) $(CFLAGS) $< -o $@ $(LIBS) $(LDFLAGS)
    
    %.o: %.c
        $(CC) $(CFLAGS) $< -c -o $@
    
    %: %.o
        $(CC) $< -o $@ $(LIBS) $(LDFLAGS)
    

    Starting from this and tweaking, you should be able to figure out the exact commandline and compile your program.

    Also, you should make sure that your PKG_CONFIG_PATH is properly updated to contain the path where you installed glib (typically in PREFIX/lib/pkgconfig).