Bazel中没有直接等效于CMake中的find_package的功能,但通过Bazel提供的外部依赖项管理工具(例如rules_foreign_cc),可以实现类似的依赖项查找和管理。
以下是一个使用rules_foreign_cc(当前名称为rules_cc)库的示例,从gRPC中找到protobuf和zlib依赖项:
WORKSPACE文件中引入rules_cc依赖项:
http_archive(
name = "rules_cc",
strip_prefix = "rules_cc-master",
sha256 = "...",
url = "https://github.com/bazelbuild/rules_cc/archive/master.zip",
)
load("@rules_cc//cc:repositories.bzl", "rules_cc_dependencies")
rules_cc_dependencies()
在BUILD文件中,使用rules_foreign_cc提供的功能来获取外部依赖项,例如在使用gRPC时获取protobuf和zlib:
load("@rules_cc//cc:defs.bzl", "cc_library")
load("@rules_cc//cc:repositories.bzl", "rules_cc_toolchains")
rules_cc_toolchains()
load("@rules_foreign_cc//cpp:defs.bzl", "cxx_link")
cxx_link( # 获取protobuf依赖项
name = "protobuf",
shared_library = "@protobuf//:protobuf",
includes = ["@protobuf//:include"],
)
cxx_link( # 获取zlib依赖项
name = "z",
shared_library = "@zlib//:zlib",
includes = ["@zlib//:include"],
)
cc_library( # gRPC库
name = "grpc",
srcs = glob(["grpc/*.cc"]),
hdrs = glob(["grpc/*.h"]),
visibility = ["//visibility:public"],
deps = [":protobuf", ":z"],
)
在上面的示例中,使用rules_foreign_cc库的cxx_link功能从外部库中获取protobuf和zlib。然后,这些依赖项可以作为依赖项传递给其他bazel构建目标,例如在声明gRPC库