7

我正在尝试在 Ubuntu 上使用以下标头编译 C 程序:http://pastebin.com/SppCXb0U。起初我一点运气都没有,但在阅读了 pkg-config 之后,我制作了这一行:

gcc `pkg-config --cflags --libs dbus-1` `pkg-config --cflags --libs glib-2.0` signals-tutorial.c

但是,它仍然不起作用并给我这个错误:

/tmp/cc3BkbdA.o: In function `filter_example':
signals-tutorial.c:(.text+0x1a3): undefined reference to `dbus_connection_setup_with_g_main'
/tmp/cc3BkbdA.o: In function `proxy_example':
signals-tutorial.c:(.text+0x29a): undefined reference to `g_type_init'
signals-tutorial.c:(.text+0x2b3): undefined reference to `dbus_g_bus_get'
signals-tutorial.c:(.text+0x323): undefined reference to `dbus_g_proxy_new_for_name'
signals-tutorial.c:(.text+0x369): undefined reference to `dbus_g_proxy_add_signal'
signals-tutorial.c:(.text+0x38a): undefined reference to `dbus_g_proxy_connect_signal'
collect2: ld returned 1 exit status

我不知道从这里做什么。

====================================

一个很好的解释-谢谢。但是,我无法让它工作。运行上面的命令(添加)会产生以下结果

gcc `pkg-config --cflags dbus-1` \
>     `pkg-config --cflags glib-2.0` \
>     signals-tutorial.c \
>     `pkg-config --libs dbus-1` \
>     `pkg-config --libs glib-2.0`
/tmp/ccjN0QMh.o: In function `filter_example':
signals-tutorial.c:(.text+0x1a3): undefined reference to `dbus_connection_setup_with_g_main'
/tmp/ccjN0QMh.o: In function `proxy_example':
signals-tutorial.c:(.text+0x29a): undefined reference to `g_type_init'
signals-tutorial.c:(.text+0x2b3): undefined reference to `dbus_g_bus_get'
signals-tutorial.c:(.text+0x323): undefined reference to `dbus_g_proxy_new_for_name'
signals-tutorial.c:(.text+0x369): undefined reference to `dbus_g_proxy_add_signal'
signals-tutorial.c:(.text+0x38a): undefined reference to `dbus_g_proxy_connect_signal'
collect2: ld returned 1 exit status
4

1 回答 1

13

您的问题不在于头文件,而在于库;关于“未定义的引用”的抱怨通常来自链接器。您需要将库配置选项放在源文件之后:

gcc `pkg-config --cflags dbus-glib-1` \
    `pkg-config --cflags dbus-1` \
    `pkg-config --cflags glib-2.0` \
    signals-tutorial.c \
    `pkg-config --libs dbus-glib-1` \
    `pkg-config --libs dbus-1` \
    `pkg-config --libs glib-2.0`

--libs选项将为编译器生成一系列-l标志,编译器会将这些标志传递给链接器。链接器将从目标文件开始从左到右解析符号(或者,在这种情况下,C 源文件足够接近),因此所有库-l开关都需要跟随您的源文件。

于 2011-04-22T01:05:58.273 回答