Kevin Zembower
Kevin Zembower

Reputation: 3

Error compiling with GLib

I'm pretty new to C programming, and am trying to work through the exercises in '21st Century C' second edition. I'm stuck on page 202, Example 9-7, unicode.c. This example starts with:

#include <glib.h>
#include <locale.h> //setlocale
#include "string_utilities.h"
#include "stopif.h"

//Frees instring for you--we can't use it for anything else.
char *localstring_to_utf8(char *instring){
    GError *e=NULL;
    setlocale(LC_ALL, ""); //get the OS's locale.
    char *out = g_locale_to_utf8(instring, -1, NULL, NULL, &e);
    free(instring); //done with the original
    Stopif(!out, return NULL, "Trouble converting from your locale to UTF-8.");
    Stopif(!g_utf8_validate(out, -1, NULL), free(out); return NULL,
            "Trouble: I couldn't convert your file to a valid UTF-8 string.");
    return out;
}

When I try to compile it with:

c99 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -g -Wall -O3 -lglib-2.0 unicode.c string_utilities.o   -o unicode

I get errors such as:

$ c99 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -g -Wall -O3 -lglib-2.0 unicode.c string_utilities.o   -o unicode
/tmp/ccBDQFiH.o: In function `localstring_to_utf8':
/home/kevin/21st_Century_C/ch09/unicode.c:29: undefined reference to `g_locale_to_utf8'
/home/kevin/21st_Century_C/ch09/unicode.c:32: undefined reference to `g_utf8_validate'
/tmp/ccBDQFiH.o: In function `main':
/home/kevin/21st_Century_C/ch09/unicode.c:48: undefined reference to `g_utf8_strlen'

This seems to indicate that the Glib library is not found, but the compiler didn't complain about this, and the Glib libraries and include files are right where I specified on the command line. I've installed the libglib2.0-dev package in addition to the libglib2.0 package (all installed with 'sudo apt-get ..'). 'pkg-config' seems to find glib-2.0 just fine.

This is all on a Ubuntu 14.04.2 system.

I can't figure out how to correct this error, and don't understand why it can't find the specific Glib functions, if it finds the glib include and lib files.

Upvotes: 0

Views: 1178

Answers (1)

Sean Bright
Sean Bright

Reputation: 120634

The order of things in the command line matter. In general it should be something like:

gcc [options] [source files] [object files] [-L stuff] [-lstuff] [-o outputfile]

So give this a whirl instead:

gcc -g -Wall -O3 -std=gnu11 `pkg-config --cflags glib-2.0` \
    unicode.c string_utilities.o `pkg-config --libs glib-2.0` \
    -o unicode

This is also covered in the Compiling GLib Applications section of the GLib Reference Manual:

$ cc hello.c `pkg-config --cflags --libs glib-2.0` -o hello

Upvotes: 2

Related Questions