How to Install C++ Libraries with Bazel - RE2 Example
A guide to building C++ libraries using Bazel, Google’s high-performance build system.
Background
I wanted to install RE2 (Google’s regular expression library), but ran into issues:
- Building with
makeon Mac required changing installation configs multiple times - Failed to build x86
.sofiles on Linux
Bazel solved these problems with consistent, reproducible builds.
What is Bazel?
Bazel is a high-performance build and test tool developed by Google. It is designed to support large-scale software projects across multiple languages and platforms.
Key Features
| Feature | Description |
|---|---|
| Caching | Caches build outputs to avoid rebuilding unchanged code |
| Parallel Execution | Builds multiple targets simultaneously |
| Sandboxing | Isolates builds for reproducibility |
| Multi-language | Supports C++, Java, Python, Go, and more |
| Cross-platform | Works on Linux, macOS, and Windows |
Why Use Bazel Over Make?
- Faster builds: Intelligent caching and parallelization
- Reproducible: Same source code produces same output everywhere
- Scalable: Designed for large codebases (Google-scale)
- Dependency management: Automatically handles transitive dependencies
Installation
Install Bazel using Homebrew (macOS) or your package manager:
# macOS
brew install bazel
# Ubuntu
sudo apt install bazel
For other platforms, see the official installation guide.
Building RE2 with Bazel
RE2 includes Bazel configuration files, making the build process simple:
# Clone the repository
git clone https://github.com/google/re2.git
cd re2
# Build the library
bazel build //:re2
The compiled library will be in bazel-bin/.
Using RE2 in Your Project
To use RE2 in your own Bazel project, add it to your WORKSPACE file:
http_archive(
name = "com_google_re2",
urls = ["https://github.com/google/re2/archive/refs/tags/2023-09-01.tar.gz"],
strip_prefix = "re2-2023-09-01",
)
Then reference it in your BUILD file:
cc_binary(
name = "my_app",
srcs = ["main.cc"],
deps = ["@com_google_re2//:re2"],
)
Troubleshooting
Build fails on first run
Bazel downloads dependencies on first build. Ensure you have internet access.
Xcode errors on macOS
Run xcode-select --install to install command line tools.
Comments