Posted on February 18, 2018

5 minute guide to Bazel, Part 1: C & C++

The aim of this guide is to get you up and running with Bazel as fast as possible. The steps will assume you have Bazel installed.

Some quick notes before we start: the most important idea about Bazel is that it is declarative.

You should never need to type out the intermediary build steps; that is the responsibility of the language/platform rule authors. The build steps are hidden away in the rule implementations so you can focus on just telling Bazel what sources to build.

Let’s get started. Each example here assumes that you’re in an empty directory called dir.

  1. Create an empty WORKSPACE file.
dir $ touch WORKSPACE
  1. Create a file called main.c and write some C in it.
// dir/main.c

#include <stdio.h>

int main(int argc, char **argv) {
  printf("Hello Bazel.\n");
  return 0;
}
  1. Write a BUILD file and tell Bazel you want an executable built from main.c.
# dir/BUILD

cc_binary(
  name = "hello_bazel",
  srcs = ["main.c"],
)

The cc_binary rule is all Bazel needs to know that you want to build C/C++ sources.

  1. Build and run the hello_bazel target, //:hello_bazel.
dir $ bazel run //:hello_bazel
...............
INFO: Analysed target //:hello_bazel (9 packages loaded).
INFO: Found 1 target...
Target //:hello_bazel up-to-date:
  bazel-bin/hello_bazel
INFO: Elapsed time: 12.423s, Critical Path: 0.44s
INFO: Build completed successfully, 5 total actions

INFO: Running command line: bazel-bin/hello_bazel
Hello Bazel.

// refers to the directory level where the WORKSPACE is. : specifies a target in a BUILD file.

  1. If you just want to build it, use bazel build instead of bazel run.
dir $ bazel build //:hello_bazel
INFO: Analysed target //:hello_bazel (9 packages loaded).
INFO: Found 1 target...
Target //:hello_bazel up-to-date:
  bazel-bin/hello_bazel
INFO: Elapsed time: 2.058s, Critical Path: 0.24s
INFO: Build completed successfully, 5 total actions

The executable is in the bazel-bin symlink: bazel-bin/hello_bazel.

dir $ cp bazel-bin/hello_bazel hello_bazel
dir $ ./hello_bazel
Hello Bazel.

That’s it!