c++ - protobuf C++ 编译器的 bazel 规则

标签 c++ protocol-buffers bazel

我正在使用 Bazel 和 Google 的 Protocol Buffer 。我想添加一个 Bazel 规则,以便我可以从 .proto 文件生成 C++ API。在 GNU make 中,我会这样做(简化示例):

%.h: %.cc
%.cc: %.proto
    protoc --cpp_out=. $<

我如何使用 Bazel 完成相同的任务(即每当 mymessage.proto 更改时生成 API)?

最佳答案

我尝试了上面的方法,但它似乎没有用,我从 protoc 那里得到了一个错误,试图创建两个目录,然后是 my-proto.h 目录不存在。相反,我做了

genrule(
    name = "my-proto-gen",
    outs = ["my-proto.pb.h my-proto.pb.cc"],
    cmd = "$(location //third_party/protobuf:protoc) --cpp_out=$(GENDIR) $<",
    srcs = ["my-proto.proto"],
    tools = ["//third_party/protobuf:protoc"],
)

cc_library(
    name = "my-proto",
    srcs = ["my-proto.pb.cc"],
    hdrs = ["my-proto.pb.h"]
)

实际上只是检查头文件是否已创建并将其创建在 bazel-genfiles 目录中。

然后您可以将原型(prototype)构建作为 :my-proto 包含在您的 cc_library 中。

更新: 要使这一切正常工作,请执行以下操作:

  1. 将以下内容添加到您的 WORKSPACE 文件中。这将下载 protobuf 库:

    http_archive(
        name = "protobuf",
        url = "https://github.com/google/protobuf/releases/download/v3.0.0/protobuf-cpp-3.0.0.zip",
        strip_prefix = "protobuf-3.0.0",
    )
    
  2. 创建一个 .bzl 文件(比如 protobuf.bzl)并放入以下内容:

    def cpp_proto(name, src):
      native.genrule(
          name = "%s-gen" % name,
          outs = ["%s.pb.cc" % name, "%s.pb.h" % name],
          cmd = "$(location @protobuf//:protoc) --cpp_out=$(GENDIR) $<",
          srcs = [src],
          tools = ["@protobuf//:protoc"],
      )
    
      native.cc_library(
          name = name,
          srcs = ["%s.pb.cc" % name],
          hdrs = ["%s.pb.h" % name],
      )
    
  3. 在您的构建文件中,添加 load(':protobuf.bzl', 'cpp_proto')

  4. 您现在可以这样使用宏:

    cpp_proto(
        name = "my-proto",
        src = "my-proto.proto"
    )
    
    cc_library(
        name = "my-program",
        srcs = ["my-program.cc"],
        deps = [
            ":my-proto",
        ],
    )
    

关于c++ - protobuf C++ 编译器的 bazel 规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39109462/

相关文章:

c++ - 请告诉我在 Bazel 中拥有多平台 WORKSPACE 的更好方法

c++ - 如何将 pretty-print 集成为 bazel 构建的一部分

c++ - 使用 C++ 读取 HTML 文本

c++ - 使用 Google Protocol Buffer - 如何在 .proto 文件中定义字段

c++ - QThreads vector

java - protobuf-net 序列化/反序列化 DateTime 和 Guid 类型

c++ - 谷歌 Protobuf 3 : Undefined Reference Errors when building with CMAKE

TensorFlow 无法编译

c++ - %ld 格式转换以实现便携性

c++ - 如何让QML窗口无边框?