如何将协议缓冲区与自动确认/自动制作一起使用?



寻找一个很好的自动会议和自动制作规则的例子来构建使用协议缓冲区的项目,这是将 protoc 添加到构建过程的最佳方式?

configure.ac

就 protobuf 库而言,它使用pkg-config,所以最好使用宏来引用它PKG_CHECK_MODULES

PKG_CHECK_MODULES(PROTOBUF, protobuf >= 2.4.0)
AC_SUBST(PROTOBUF_LIBS)
AC_SUBST(PROTOBUF_CFLAGS)
AC_SUBST(PROTOBUF_VERSION)

并检查路径中的protoc命令。这是一个非常基本的检查,它是否在路径中:

AC_CHECK_PROG([PROTOC], [protoc], [protoc])
AS_IF([test "x${PROTOC}" == "x"],
[AC_MSG_ERROR([ProtoBuf compiler "protoc" not found.])])

或者,允许用户使用--with-protoc=/path/to/protoc或使用环境变量PROTOC指定不同的protoc

# ProtoBuf compiler.
# First, specify with --with-protoc=/path/of/protoc.
# Or, specify with env variable PROTOC.
# If neither of the above, find it in the path.
#AC_MSG_CHECKING([for ProtoBuf compiler protoc])
AC_ARG_WITH([protoc],
[AS_HELP_STRING([--with-protoc=/path/of/protoc],
[Location of the protocol buffers compiler protoc. Defaults to looking on path.])],
[PROTOC="$withval"],
[ AS_IF([test "x${PROTOC}" == "x"],
[AC_PATH_PROG([PROTOC], [protoc], [no])])
]
)
#AC_MSG_RESULT([${PROTOC}])
AS_IF([test "${PROTOC}" == "no"], [AC_MSG_ERROR([ProtoBuf compiler "protoc" not found.])])

Makefile.am

添加规则以生成proto文件:

%.pb.cc %.pb.h: %.proto
$(PROTOC) --proto_path=$(srcdir) --cpp_out=$(builddir) $^

使用dist_noinst_DATA指定 protobuf 源文件。这对于确保它们捆绑在用make dist制作的源代码分发.tar.gz文件中是必要的。

dist_noinst_DATA = whatever.proto

(注意:对于较新版本的 autoconf/automake,可能需要使用@builddir@而不是$(builddir)

使用前缀和$(builddir)路径指定生成的文件nodist_

nodist_myprog_SOURCES = $(builddir)/whatever.pb.cc $(builddir)/whatever.pb.h

并用make clean清洁它们:

MOSTLYCLEANFILES = whatever.pb.cc whatever.pb.h

使用BUILT_SOURCES处理构建头文件的依赖关系:

BUILT_SOURCES = whatever.pb.h

编译器标志可能需要引用构建目录才能找到头文件(才能在 VPATH 构建中工作):

AM_CPPFLAGS += -I$(builddir)

这似乎有效:

configure.ac:

AC_ARG_WITH([protobuf-libdir],
[AS_HELP_STRING([--with-protobuf-libdir=LIB_DIR],
[location of the protocol buffers libraries, defaults to /usr/lib])],
[PROTOBUF_LIBDIR="$withval"],
[PROTOBUF_LIBDIR='/usr/lib'])
AC_SUBST([PROTOBUF_LIBDIR])
LDFLAGS="$LDFLAGS -L$PROTOBUF_LIBDIR"
AC_CHECK_LIB([protobuf], [main], [], [AC_MSG_ERROR([cannot find protobuf library])])
AC_ARG_WITH([protoc],
[AS_HELP_STRING([--with-protoc=PATH],
[location of the protoc protocol buffer compiler binary, defaults to protoc])],
[PROTOC="$withval"],
[PROTOC='protoc'])
AC_SUBST([PROTOC])

Makefile.am:

%.pb.cc %.pb.h: %.proto
$(PROTOC) --proto_path=$(dir $^) --cpp_out=$(dir $^) $^

然后将 .pb.cc 文件添加到源。

最新更新