Trismegistos
Trismegistos

Reputation: 3882

Can not link dbus with c++

I have simple program which includes dbus and uses basic functions e.g.:

 DBusError err;
 dbus_error_init(&err);

When I try to compile the program

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

I get following errors:

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

I do not understand it. I tried to compile similiar application but written in C and everything compiled and linked.

Upvotes: 1

Views: 3094

Answers (1)

Gluttton
Gluttton

Reputation: 5978

Just put -l options at the end:

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

Here is related question: What is the proper sequence of options for gcc & the importance of that sequence?

This behaviour is expected and according to documentations:

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.
...

Upvotes: 2

Related Questions