Skip to main content

Use non-Bazel Libraries in Bazel Project

·216 words·
Techniques Bazel
komori-n
Author
komori-n

One may want to use external libraries that Bazel does not manage when using Bazel.

cc_binary(
  name = "hello-world",
  srcs = ["main.cpp"],
  deps = [
    # external libraries that are not managed by bazel
  ],
)

To use local files in Bazel, one can use new_local_repository. 1

new_local_repository is a function that can be used in WORKSPACE files, which adds a BUILD file virtually and make a local directory Bazel project. One can specify the BUILD file by the option build_file orbuild_file_content. For example, if one wants to use OpenSSL in its local storage, a sample code with build_file is the following:

# WORKSPACE.bazel
new_local_repository(
  name = "openssl",
  path = "/opt/homebrew/Cellar/openssl@3/3.0.5",
  build_file = "openssl.BUILD",
)
# openssl.BUILD
cc_library(
  name = "lib",
  hdrs = glob(["include/**/*.h"]),
  srcs = glob(["lib/*.dylib"]),
  strip_include_prefix = "include",
  visibility = ["//visibility:public"],
)

A sample code with build_file_content is the following:

# WORKSPACE.bazel
new_local_repository(
  name = "openssl",
  path = "/opt/homebrew/Cellar/openssl@3/3.0.5",
  build_file_content = """
cc_library(
  name = "lib",
  hdrs = glob(["include/**/*.h"]),
  srcs = glob(["lib/*.dylib"]),
  strip_include_prefix = "include",
  visibility = ["//visibility:public"],
)""",
)

In the latter case, one needs to set proper indents, or it will not be recognized as a correct BUILD file.


  1. To use remote files managed by Git build_file or build_file_content in git_repository can be used the same way as this page. ( ref ↩︎

Related

Throw away pack expansion results in C++
·524 words
Techniques C++
Handle permutations with duplicates at compile time
·594 words
Techniques C++
`Constraints` improves readability of SFINAE code
·322 words
Techniques C++ SFINAE