c++ - 无法将 dbus 与 C++ 链接

标签 c++ linux linker g++ dbus

我有一个简单的程序,其中包括 dbus 并使用基本功能,例如:

 DBusError err;
 dbus_error_init(&err);

当我尝试编译程序时

g++ -Wall --std=c++11 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include  -ldbus-1 main.cpp

我收到以下错误:

main.cpp:(.text+0x4b): undefined reference to `dbus_error_init'
main.cpp:(.text+0x5a): undefined reference to `dbus_bus_get_private'
main.cpp:(.text+0x79): undefined reference to `dbus_error_free'
main.cpp:(.text+0xf4): undefined reference to `dbus_connection_set_exit_on_disconnect'
main.cpp:(.text+0x114): undefined reference to `dbus_bus_request_name'
main.cpp:(.text+0x123): undefined reference to `dbus_error_is_set'
main.cpp:(.text+0x138): undefined reference to `dbus_error_free'
collect2: error: ld returned 1 exit status

我不明白。我尝试编译类似的应用程序,但它是用 C 语言编写的,所有内容都经过编译和链接。

最佳答案

只需将 -l 选项放在末尾即可:

g++ -Wall --std=c++11 -I/usr/include/dbus-1.0 -I/usr/lib/x86_64-linux-gnu/dbus-1.0/include main.cpp -ldbus-1

这是相关问题:What is the proper sequence of options for gcc & the importance of that sequence?

根据文档,这种行为是预期的:

man g++

...
You can mix options and other arguments. For the most part, the order you use doesn't matter. Order does matter when you use several options of the same kind; for example, if you specify -L more than once, the directories are searched in the order specified. Also, the placement of the -l option is significant.
...
-llibrary
...
It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in z, those functions may not be loaded.
...

关于c++ - 无法将 dbus 与 C++ 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24884679/

相关文章:

c++ - 错误: expected unqualified-id before return in c++

c++ - Linux 默认库

linux - SSH无密码登录失败

c++ - 静态库如何链接到依赖项?

C++11 为 std::chrono::time_point 添加流输出运算符

c++ - 静态链接 MFC 时未修改的 Visual Studio 2012 MFC 模板中的链接错误

php - 努力在 Centos 上安装 PHP pecl

c - 所有 fork 函数的返回值有什么区别?

c++ - 将可执行文件与静态库的完整路径链接起来

c++ - Geany 中的链接类