TExcelTAD
Home › Monorepo Builds: Bazel (+ Buck2 & Pants) › C++: cc_library, cc_binary, cc_test

C++: cc_library, cc_binary, cc_test

The C++ rules come from rules_cc (version 0.2.27 here). Three of them cover most code:

Rule Produces Key attributes
cc_library lib<name>.a and lib<name>.so (built on demand) plus the headers it exports srcs, hdrs, deps, implementation_deps, copts, defines, local_defines, includes, strip_include_prefix, linkstatic, alwayslink
cc_binary an executable srcs, deps, copts, linkopts, data, linkstatic (default True: dependencies are linked statically)
cc_test a test executable that bazel test runs; exit code 0 = pass same as cc_binary, plus size, timeout, shard_count, args, env

If you know CMake, deps is target_link_libraries, hdrs is the PUBLIC part of a target's sources, srcs the PRIVATE part, and defines/local_defines are target_compile_definitions PUBLIC/PRIVATE (Usage Requirements in the CMake course explains the idea). The big difference: Bazel enforces it, as the next lesson shows.

A library, a binary and a test

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p geometry app
cat > geometry/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test")

cc_library(
    name = "geometry",
    srcs = ["area.cc"],
    hdrs = ["area.h"],
    visibility = ["//visibility:public"],
)

cc_test(
    name = "area_test",
    size = "small",
    srcs = ["area_test.cc"],
    deps = [":geometry"],
)
EOF
cat > geometry/area.h <<'EOF'
#pragma once
double circle_area(double r);
double square_area(double side);
EOF
cat > geometry/area.cc <<'EOF'
#include "geometry/area.h"
double circle_area(double r) { return 3.14159265 * r * r; }
double square_area(double side) { return side * side; }
EOF
cat > geometry/area_test.cc <<'EOF'
#include <cmath>
#include <cstdio>
#include "geometry/area.h"
int main() {
  int failures = 0;
  if (square_area(3) != 9) { std::puts("square_area(3) != 9"); ++failures; }
  if (std::fabs(circle_area(1) - 3.14159) > 1e-4) { std::puts("circle_area(1) wrong"); ++failures; }
  std::printf("%d failure(s)\n", failures);
  return failures == 0 ? 0 : 1;
}
EOF
cat > app/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(name = "areas", srcs = ["main.cc"], deps = ["//geometry"])
EOF
cat > app/main.cc <<'EOF'
#include <cstdio>
#include "geometry/area.h"
int main() { std::printf("circle(2) = %.2f, square(2) = %.2f\n", circle_area(2), square_area(2)); }
EOF
bazel run //app:areas
bazel test //geometry:area_test
cat bazel-testlogs/geometry/area_test/test.log
Starting local Bazel server (9.3.1) and connecting to it...
INFO: Analyzed target //app:areas (94 packages loaded, 548 targets configured).
INFO: Found 1 target...
Target //app:areas up-to-date:
  bazel-bin/app/areas
INFO: Elapsed time: 3.724s, Critical Path: 0.08s
INFO: 8 processes: 5 internal, 3 processwrapper-sandbox.
INFO: Build completed successfully, 8 total actions
INFO: Running command line: bazel-bin/app/areas
circle(2) = 12.57, square(2) = 4.00
INFO: Analyzed target //geometry:area_test (4 packages loaded, 410 targets configured).
INFO: Found 1 test target...
Target //geometry:area_test up-to-date:
  bazel-bin/geometry/area_test
INFO: Elapsed time: 0.647s, Critical Path: 0.22s
INFO: 10 processes: 6 internal, 5 processwrapper-sandbox.
INFO: Build completed successfully, 10 total actions
//geometry:area_test                                                     PASSED in 0.0s

Executed 1 out of 1 test: 1 test passes.
exec ${PAGER:-/usr/bin/less} "$0" || exit 1
Executing tests from //geometry:area_test
-----------------------------------------------------------------------------
0 failure(s)

Points to notice:

  • Headers are included with their workspace-relative path ("geometry/area.h"): Bazel adds the execution root to the include path (-iquote .), so every header has exactly one name across the repository.
  • deps = ["//geometry"] is short for //geometry:geometry; naming the main target after its package is a common convention.
  • bazel test builds the test, runs it in a sandbox and keeps its output in bazel-testlogs/<package>/<target>/test.log (and a JUnit-style test.xml). The log's first line, exec ${PAGER:-/usr/bin/less} "$0", is a trick that lets you execute the log file to page through it. A passing test's output isn't shown unless you ask for it; the testing lesson covers --test_output.

What a cc_library builds

cc_library doesn't decide between static and shared: it produces both kinds of output, and the binary decides how to link. With the default linkstatic = True, a cc_binary links the libraries' object files statically:

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir -p geometry app
printf 'load("@rules_cc//cc:defs.bzl", "cc_library")\ncc_library(name = "geometry", srcs = ["area.cc"], hdrs = ["area.h"], visibility = ["//visibility:public"])\n' > geometry/BUILD.bazel
printf '#pragma once\ndouble square_area(double side);\n' > geometry/area.h
printf '#include "geometry/area.h"\ndouble square_area(double side) { return side * side; }\n' > geometry/area.cc
cat > app/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary")
cc_binary(name = "static_app", srcs = ["main.cc"], deps = ["//geometry"])
cc_binary(name = "dynamic_app", srcs = ["main.cc"], deps = ["//geometry"], linkstatic = False)
EOF
printf '#include <cstdio>\n#include "geometry/area.h"\nint main() { std::printf("%%.1f\\n", square_area(1.5)); }\n' > app/main.cc
bazel build //geometry 2>&1 | sed -n '/up-to-date/,/Elapsed/p' | grep -v Elapsed
bazel build //app:all 2>/dev/null
./bazel-bin/app/static_app; ./bazel-bin/app/dynamic_app
ldd bazel-bin/app/dynamic_app | grep -o 'libgeometry_Slibgeometry.so' | sort -u
ldd bazel-bin/app/static_app | grep -c geometry
Target //geometry:geometry up-to-date:
  bazel-bin/geometry/libgeometry.a
  bazel-bin/geometry/libgeometry.so
2.2
2.2
libgeometry_Slibgeometry.so
0

The shared library got a mangled name (libgeometry_Slibgeometry.so, from the package path) and lives in a _solib_k8 directory next to the binary; Bazel sets the binary's rpath so it finds it. You rarely use linkstatic = False in production; it's mostly a way to speed up linking of large test binaries. For a shared library you ship, use cc_shared_library.

Compilation modes and flags

Flag Effect
-c fastbuild (default) no optimisation, no debug info: fastest to build
-c dbg -g, no optimisation
-c opt -O2 -DNDEBUG (with the auto-configured GCC toolchain)
--copt=-Wextra, --cxxopt=-std=c++20, --linkopt=… extra flags for every C/C++ compile or link in the build
--per_file_copt=//geometry/.*@-O3 flags for a subset of files

Each mode writes to its own output directory (bazel-out/k8-fastbuild, k8-dbg, k8-opt), so switching modes doesn't throw away the other mode's outputs.

bash · try it yourself
mkdir ws && cd ws
echo 'bazel_dep(name = "rules_cc", version = "0.2.27")' > MODULE.bazel
mkdir app
cat > app/BUILD.bazel <<'EOF'
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
cc_library(name = "config", hdrs = ["config.h"], defines = ["SHOP_API=2"], local_defines = ["CONFIG_INTERNAL"])
cc_binary(name = "app", srcs = ["main.cc"], deps = [":config"], copts = ["-Wshadow"])
EOF
echo '#pragma once' > app/config.h
cat > app/main.cc <<'EOF'
#include <cstdio>
#include "app/config.h"
int main() {
#ifdef CONFIG_INTERNAL
  std::puts("CONFIG_INTERNAL leaked");
#endif
#ifdef NDEBUG
  const char* mode = "NDEBUG";
#else
  const char* mode = "asserts on";
#endif
  std::printf("SHOP_API=%d, %s\n", SHOP_API, mode);
}
EOF
bazel run //app 2>/dev/null
bazel run -c opt //app 2>/dev/null
ls -d bazel-out/k8-*
SHOP_API=2, asserts on
SHOP_API=2, NDEBUG
bazel-out/k8-fastbuild
bazel-out/k8-opt

defines propagate to everything that depends on the library (here the binary sees SHOP_API=2), while local_defines stay inside the library. Prefer local_defines unless a header really needs the macro: every propagated define changes the command line, and so the cache key, of every dependent compile.

Note: The course image auto-configures a C++ toolchain from the system GCC 13 (rules_cc's cc_configure extension). That's convenient but not hermetic: a machine with another GCC gets different results. Real projects often register a hermetic toolchain (for example toolchains_llvm or hermetic_cc_toolchain); see Toolchain Resolution.

Test yourself

How does a source file include geometry/area.h from package //geometry?

  1. #include "area.h" always
  2. #include "geometry/area.h", the path from the workspace root
  3. #include <geometry>
  4. Only through a -I flag in copts

What is the difference between defines and local_defines on a cc_library?

  1. None
  2. defines propagate to dependents; local_defines apply only to the library's own sources
  3. local_defines propagate; defines don't
  4. defines are for C, local_defines for C++

Where does bazel build -c opt put its outputs?

  1. Over the fastbuild outputs
  2. In a separate configuration directory such as bazel-out/k8-opt
  3. In /tmp
  4. In the source tree