Migrating a CMake Project
Most C++ code that moves to Bazel comes from CMake. The move is rarely technical in the hard sense: CMake targets map to Bazel targets quite directly. The work is in making implicit things explicit (headers, generated files, compiler flags spread across directories) and in running both systems side by side until everyone trusts the new one. Modern CMake is the reference for the CMake side of this lesson.
The mapping
| CMake | Bazel |
|---|---|
project(), top-level CMakeLists.txt |
MODULE.bazel (+ .bazelrc for global flags) |
one CMakeLists.txt per directory |
one BUILD.bazel per package (often finer-grained) |
| `add_library(x STATIC | SHARED …)` |
add_executable |
cc_binary |
add_test / CTest |
cc_test + bazel test |
target_link_libraries(x PUBLIC y) |
deps = ["//y"] |
target_link_libraries(x PRIVATE y) |
implementation_deps = ["//y"] |
target_include_directories(x PUBLIC include) |
hdrs + strip_include_prefix = "include" (or includes) |
target_compile_definitions(PUBLIC/PRIVATE) |
defines / local_defines |
target_compile_options, CMAKE_CXX_FLAGS |
copts, --copt/--cxxopt in .bazelrc |
CMAKE_BUILD_TYPE=Release |
-c opt |
option(WITH_SSL …) |
a bool_flag + config_setting + select() |
configure_file() |
expand_template (bazel_skylib) or a small rule/genrule |
add_custom_command (codegen) |
genrule or a custom rule |
find_package(fmt) / FetchContent |
bazel_dep(name = "fmt", …) from the BCR; otherwise http_archive + a BUILD file |
| a dependency that only builds with CMake | rules_foreign_cc's cmake() rule (wraps a CMake build as one action) |
| toolchain files | platforms + registered toolchains |
install(), CPack |
rules_pkg (pkg_tar, pkg_deb) |
A worked example
The CMake project (not run here: the Bazel image has no CMake):
calc/
├── CMakeLists.txt
├── src/
│ ├── CMakeLists.txt add_library(calc …), configure_file(version.h.in)
│ ├── include/calc/calc.h
│ ├── calc.cc
│ └── version.h.in
├── tools/CMakeLists.txt add_executable(calc_cli …)
└── tests/CMakeLists.txt add_executable(calc_test …) + add_test# src/CMakeLists.txt
configure_file(version.h.in ${CMAKE_CURRENT_BINARY_DIR}/generated/calc/version.h)
add_library(calc calc.cc)
target_include_directories(calc
PUBLIC include
PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated)
target_compile_definitions(calc PRIVATE CALC_INTERNAL=1)
target_compile_features(calc PUBLIC cxx_std_17)The Bazel version, built and tested for real. Each CMakeLists.txt becomes a BUILD.bazel, the configure_file becomes a genrule, and the include directories become strip_include_prefix:
mkdir -p calc/src/include/calc calc/tools calc/tests && cd calc
cat > MODULE.bazel <<'EOF'
module(name = "calc", version = "1.3.0")
bazel_dep(name = "rules_cc", version = "0.2.27")
EOF
cat > .bazelrc <<'EOF'
build --cxxopt=-std=c++17
test --test_output=errors
EOF
# --- src: the library (was src/CMakeLists.txt)
cat > src/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_library")
genrule( # was configure_file(version.h.in ...)
name = "version_h",
srcs = ["version.h.in"],
outs = ["calc/version.h"],
cmd = "sed 's/@CALC_VERSION@/1.3.0/' lt; > $@",
)
cc_library(
name = "calc",
srcs = ["calc.cc", ":version_h"], # generated header is private, like PRIVATE generated/
hdrs = ["include/calc/calc.h"],
strip_include_prefix = "include", # was target_include_directories(PUBLIC include)
local_defines = ["CALC_INTERNAL=1"], # was target_compile_definitions(PRIVATE ...)
visibility = ["//visibility:public"],
)
EOF
printf '#pragma once\nnamespace calc {\nint add(int a, int b);\nconst char* version();\n}\n' > src/include/calc/calc.h
printf '#define CALC_VERSION "@CALC_VERSION@"\n' > src/version.h.in
cat > src/calc.cc <<'EOF'
#include "calc/calc.h"
#include "src/calc/version.h"
namespace calc {
int add(int a, int b) { return a + b; }
const char* version() { return CALC_INTERNAL ? CALC_VERSION : "?"; }
}
EOF
# --- tools and tests
printf 'load("@rules_cc//cc:defs.bzl", "cc_binary")\ncc_binary(name = "calc_cli", srcs = ["main.cc"], deps = ["//src:calc"])\n' > tools/BUILD.bazel
printf '#include <cstdio>\n#include "calc/calc.h"\nint main() { std::printf("calc %%s: 2 + 3 = %%d\\n", calc::version(), calc::add(2, 3)); }\n' > tools/main.cc
printf 'load("@rules_cc//cc:defs.bzl", "cc_test")\ncc_test(name = "calc_test", size = "small", srcs = ["calc_test.cc"], deps = ["//src:calc"])\n' > tests/BUILD.bazel
printf '#include "calc/calc.h"\nint main() { return calc::add(2, 2) == 4 ? 0 : 1; }\n' > tests/calc_test.cc
bazel run //tools:calc_cli 2>/dev/null
bazel test //... 2>&1 | grep -E 'PASSED|FAILED'
echo "== what a dependent sees"
bazel cquery //src:calc --output=starlark --starlark:expr='[f.path for f in providers(target)["@@rules_cc+//cc/private:cc_info.bzl%CcInfo"].compilation_context.direct_public_headers]' 2>/dev/nullcalc 1.3.0: 2 + 3 = 5
//tests:calc_test PASSED in 0.0s
== what a dependent sees
["bazel-out/k8-fastbuild/bin/src/_virtual_includes/calc/calc/calc.h", "src/include/calc/calc.h"]
Two details made explicit by the migration:
- The generated
version.his insrcs, so it is private to the library, just like thePRIVATEinclude directory in CMake. The library's public headers (direct_public_headers) are onlycalc.h: the source file plus the symlink in the virtual include directory (_virtual_includes/calc/calc/calc.h) thatstrip_include_prefixcreated, which is what makes#include "calc/calc.h"work for dependents. - In CMake,
tools/could have includedversion.hby accident if the generated directory leaked into its include path. In Bazel it can't: it isn't in the dependents' inputs.
Strategy for a real repository
- Inventory. List targets, generated files, compiler flags and external dependencies (
cmake --graphviz=deps.dotgives the target graph). Decide on BCR modules for third-party code (fmt,abseil-cpp,googletest,boost.*are all there) andrules_foreign_cconly for what has no Bazel build. - Bottom-up. Convert leaf libraries first, keep CMake building everything; CI builds with both.
- Make the global flags explicit in
.bazelrc(--cxxopt=-std=c++20, warnings) and per-targetcoptsonly where CMake had them. - Fine-grained targets. A 500-file CMake library can become 20 Bazel libraries; finer targets give better caching and enforceable boundaries, but split after the first working conversion.
- Compare outputs. Run the same tests under both systems; compare binary sizes and symbols (
nm) for surprises such as missing defines. - Switch, then delete the CMake files so they can't rot.
Note: Tools exist to generate a first draft of BUILD files from a compile database (
compile_commands.json), but the result needs the same review as a hand-written conversion. Budget for the review, not the typing.
Test yourself
What is the Bazel equivalent of target_link_libraries(x PRIVATE y)?
- deps = ["//y"]
- implementation_deps = ["//y"]
- linkopts = ["-ly"]
- data = ["//y"]
How did the example replace configure_file()?
- With CMake inside Bazel
- With a genrule (expand_template from bazel_skylib would also work)
- By committing the generated file
- It isn't possible
A dependency only has a CMake build and no BUILD files. What are the options?
- Rewrite it
- Use a BCR module if one exists, else http_archive with a hand-written BUILD file, or rules_foreign_cc's cmake() rule
- Vendor the binary only
- Skip it