Bazel使用:编译protobuf

Bazel安装参考:(https://blog.csdn.net/qq_41347613/article/details/107856853)

1、构建项目

新建文件夹,编写WORKSPACE文件
在这里插入图片描述
文件中添加如下内容:

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

# rules_cc defines rules for generating C++ code from Protocol Buffers.
http_archive(
    name = "rules_cc",
    sha256 = "35f2fb4ea0b3e61ad64a369de284e4fbbdcdba71836a5555abb5e194cf119509",
    strip_prefix = "rules_cc-624b5d59dfb45672d4239422fa1e3de1822ee110",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_cc/archive/624b5d59dfb45672d4239422fa1e3de1822ee110.tar.gz",
        "https://github.com/bazelbuild/rules_cc/archive/624b5d59dfb45672d4239422fa1e3de1822ee110.tar.gz",
    ],
)

# rules_proto defines abstract rules for building Protocol Buffers.
http_archive(
    name = "rules_proto",
    sha256 = "2490dca4f249b8a9a3ab07bd1ba6eca085aaf8e45a734af92aad0c42d9dc7aaf",
    strip_prefix = "rules_proto-218ffa7dfa5408492dc86c01ee637614f8695c45",
    urls = [
        "https://mirror.bazel.build/github.com/bazelbuild/rules_proto/archive/218ffa7dfa5408492dc86c01ee637614f8695c45.tar.gz",
        "https://github.com/bazelbuild/rules_proto/archive/218ffa7dfa5408492dc86c01ee637614f8695c45.tar.gz",
    ],
)

load("@rules_cc//cc:repositories.bzl", "rules_cc_dependencies")
rules_cc_dependencies()

load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains")
rules_proto_dependencies()
rules_proto_toolchains()

编写msg.proto文件:

package Im;
message Content
{
  required int32  id = 1;
  required string str = 2;
  optional int32  opt = 3;
}

编写main.cpp文件:

#include 
#include "msg.pb.h"

int main() {
  Im::Content msg ;
  msg.set_id(10);
  msg.set_str("zhangzq"),
  std::cout << msg.id() << '\n' << msg.str() << std::endl;
  return 0;
}

编写BUILD文件
在这里插入图片描述添加如下内容:

load("@rules_cc//cc:defs.bzl", "cc_proto_library")
load("@rules_proto//proto:defs.bzl", "proto_library")

cc_proto_library(
    name = "msg_proto",
    deps = [":msg_proto_lib"],
)

proto_library(
    name = "msg_proto_lib",
    srcs = ["msg.proto"],
)

cc_binary(
    name = "main",
    srcs = ["main.cpp"],
    deps = ["msg_proto"],
)

2、编译项目

运行以下指令进行编译:

$ bazel build :main

Bazel使用:编译protobuf_第1张图片运行以下指令进行测试:

$ bazel-bin/main

在这里插入图片描述

3、编译报错

3.1错误为:error while loading shared libraries: libprotobuf.so.8: cannot open shared object file: No such file or directory

找不到对应的库文件,可重新安装配置protobuf:参考(https://blog.csdn.net/qq_41347613/article/details/107815059)

你可能感兴趣的:(Google工具,linux,protobuf,google)