As developers know, virtually all compilers support the notion
of compilation mode, e.g.. whether to compile the code in debug
or release mode. In Bazel, this concept is built natively into
the build system itself. When compiling software using bazel build
,
one can select a compilation mode using the --compilation_mode
(often shorted to -c
) flag.
The compilation modes supported by Bazel are:
fastbuild
means build as fast as possible: generate minimal debugging information (e.g. ingcc
, build with-gmlt -Wl,-S
), and don’t optimize. This is the default.dbg
means build with debugging enabled (e.g. ingcc
, build with-g
), so that you can use a debugger such asgdb
opt
means build with optimization enabled and withassert()
calls disabled (e.g. ingcc
, build with-O2 -DNDEBUG
).
These compilation modes can and should be respected by all custom rules so
that a Bazel user can use a single bazel build -c
command to compile any
software in either fastbuild
, dbg
, or opt
mode. In addition, a rule
author can also implement an optional compilation mode attribute which can
be used to override the mode on an individual target.
Here’s how to do so.
First, start with a basic build rule:
|
|
Next, add an attribute to the rule which a user can optionally set to set the compilation mode on a particular target:
|
|
Next, in the rule implementation, determine the effective compilation mode as follows:
|
|
A user of the rule can either specify the compilation mode on an individual target as follows:
|
|
Alternatively, they can affect all targets globally with the build -c
option,
as in bazel build -c opt //...
.