c - 使用 GLib 编译时出错

标签 c compilation libraries glib

我是 C 编程的新手,正在尝试完成“21 世纪 C”第二版中的练习。我卡在第 202 页,例 9-7,unicode.c。这个例子开始于:

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

当我尝试编译它时:

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

我收到如下错误:

$ 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'

这似乎表明找不到 Glib 库,但编译器并没有对此报错,Glib 库和包含文件就在我在命令行中指定的位置。除了 libglib2.0 软件包之外,我还安装了 libglib2.0-dev 软件包(全部使用“sudo apt-get ..”安装)。 'pkg-config' 似乎发现 glib-2.0 就好了。

这一切都在 Ubuntu 14.04.2 系统上进行。

我不知道如何纠正这个错误,不明白为什么它找不到特定的 Glib 函数,如果它找到 glib 包含和 lib 文件。

最佳答案

命令行中的顺序很重要。一般来说,它应该是这样的:

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

所以试一试:

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

这也包含在 Compiling GLib Applications 中节GLib Reference Manual :

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

关于c - 使用 GLib 编译时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29173306/

相关文章:

haskell - 分析 Haskell 代码但不包括库分析信息

c - 如何修复不完整的结构类型

c - 从 C 中的无符号整数打印一个字节

c - 交换 2 个空指针地址

c - 链接列表和结构

c++ - 在新的 C++ 库中处理多种字符串类型

optimization - 如果我优化大小(z)而不是速度(3),我将更改什么速度增益?

java - linux下如何编译ogre4j

linux - linux下如何通过编译源码安装devels

components - 如何实现像 youtube 这样的网站?