bazel 条件编译选择不同的库

WORKSPACE文件

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

git_repository(
    name = "com_google_protobuf",
    remote = "https://github.com/protocolbuffers/protobuf.git",
    tag = "v3.9.0",
)

http_archive(
    name = "com_github_brpc_brpc",
    urls = [
        "https://github.com/apache/incubator-brpc/archive/1.0.0.tar.gz",
    ],
    strip_prefix = "brpc-1.0.0",
)

http_archive(
    name = "com_github_grpc_grpc",
    urls = [
        "https://github.com/grpc/grpc/archive/v1.56.0.tar.gz",
    ],
    strip_prefix = "grpc-1.56.0",
)
load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
grpc_deps()
load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
grpc_extra_deps()

BUILD文件

package(default_visibility = ["//visibility:public"])

#设置条件
config_setting(
    name = "with_brpc_client",
    define_values = {"client_channel": "brpc"},
    visibility = ["//visibility:public"],
)

config_setting(
    name = "with_grpc_client",
    define_values = {"client_channel": "grpc"},
    visibility = ["//visibility:public"],
)

cc_binary(
    name = "memory_leak",
    linkopts = ["-ltcmalloc",],
    srcs = ["memory_leak.cpp"],
    deps = [
        "@com_google_protobuf//:protobuf",
    ] + select({
        ":with_brpc_client": ["@com_github_brpc_brpc//:brpc"],
        ":with_grpc_client": ["@com_github_grpc_grpc//:grpc"],
        "//conditions:default": ["@com_github_brpc_brpc//:brpc"], #默认brpc
    }),
)

.bazelrc文件

build --copt=-O2
build --copt=-g
build --cxxopt=-std=c++17
build --define=client_channel=grpc

通过define选择用grpc还是brpc

memory_leak.cpp文件

#include 
  
int func() {
    int *p = new int(10);
    return 0;
}

int main() {
    std::cout << "memory leak test" << std::endl;
    return func();
}

注意这个只是模版,由于缺少好多库,导致brpc编译不过

你可能感兴趣的:(C++,c++)