上一讲我们在用d-feet观察dbus的同时,介绍了dbus的一些基本概念:包括消息总线,然后是总线->总线上的连接->应用中的对象->对象提供的接口->接口的方法和信号。 在进一步讨论细节前,让我们先看看代码。
hello-dbus3是个很简单的例子,它提供了一个加法接口,上一讲我们在d-feet中用过这个接口。 将hello-dbus3-0.1.tar.gz解包后会看到一个标准的autotool工程,这是用make distcheck创建的发布包,包含了很多自动生成的文件。我们可以工程目录执行:
$ ./clean.sh
clean.sh删除自动生成的文件,剩下的文件就都是我手工创建的了:
$ find . -type f ./clean.sh ./Makefile.am ./autogen.sh ./src/Makefile.am ./src/example-service.c ./src/example-client.c ./src/example-service.xml ./configure.ac
./clean.sh已经说过。./autogen.sh调用一些autotool创建工程:
touch `find .` aclocal autoconf autoheader touch NEWS README AUTHORS ChangeLog automake --add-missing
autotool的工程基本上都是这样。第一句touch比较奇怪,这是因为我习惯在windows编辑文件然后传到虚拟机,touch一下是避免出现比虚拟机当前时间还要新的文件。 ./Makefile.am只是列出子目录和额外的发布文件:
SUBDIRS = src EXTRA_DIST = autogen.sh clean.sh
主要的工程配置其实是在./src/Makefile.am中,不过在看它之前,我们先看看configure.ac。
configure.ac的内容如下:
AC_INIT() AM_INIT_AUTOMAKE(hello-dbus3, 0.1) AM_CONFIG_HEADER(config.h) AC_PROG_CC # 检查dbus库 PKG_CHECK_MODULES(DBUS, dbus-1 >= 1.1, have_dbus=yes, have_dbus=no) if test x$have_dbus = xno ; then AC_MSG_ERROR([DBus development libraries not found]) fi AM_CONDITIONAL(HAVE_DBUS, test x$have_dbus = xyes) AC_SUBST(DBUS_CFLAGS) AC_SUBST(DBUS_LIBS) # 检查dbus-glib库 PKG_CHECK_MODULES(DBUS_GLIB, gobject-2.0 >= 2.6, have_glib=yes, have_glib=no) if test x$have_glib = xno ; then AC_MSG_ERROR([GLib development libraries not found]) fi AM_CONDITIONAL(HAVE_GLIB, test x$have_glib = xyes) AC_SUBST(DBUS_GLIB_CFLAGS) AC_SUBST(DBUS_GLIB_LIBS) AC_OUTPUT([Makefile src/Makefile])
值得注意的就是检查dbus库和dbus-glib库的宏。可以看到configure.ac导出了 DBUS_CFLAGS、DBUS_LIBS、DBUS_GLIB_CFLAGS和DBUS_GLIB_LIBS。
./src/Makefile.am的内容如下:
INCLUDES = \ $(DBUS_CFLAGS) \ $(DBUS_GLIB_CFLAGS) \ LIBS = \ $(DBUS_LIBS) \ $(DBUS_GLIB_LIBS) \ -ldbus-glib-1 # example-service noinst_PROGRAMS = example-service example_service_SOURCES = example-service.c BUILT_SOURCES = example-service-glue.h example-service-glue.h: example-service.xml $(LIBTOOL) --mode=execute dbus-binding-tool --prefix=test_obj --mode=glib-server --output=example-service-glue.h example-service.xml CLEANFILES = $(BUILT_SOURCES) EXTRA_DIST = example-service.xml # example-client noinst_PROGRAMS += example-client example_client_SOURCES= example-client.c
这个工程要编译两个程序:example-service和example-client。其中比较特殊的就是用dbus-binding-tool的使用。 我们用example-service.xml描述接口,dbus-binding-tool根据example-service.xml生成example-service-glue.h。 我们通常不需要修改example-service-glue.h。