# FAQ
Source: https://bazel.build/about/faq
If you have questions or need support, see [Getting Help](/help).
## What is Bazel?
Bazel is a tool that automates software builds and tests. Supported build tasks include running compilers and linkers to produce executable programs and libraries, and assembling deployable packages for Android, iOS and other target environments. Bazel is similar to other tools like Make, Ant, Gradle, Buck, Pants and Maven.
## What is special about Bazel?
Bazel was designed to fit the way software is developed at Google. It has the following features:
* Multi-language support: Bazel supports [many languages](/reference/be/overview), and can be extended to support arbitrary programming languages.
* High-level build language: Projects are described in the `BUILD` language, a concise text format that describes a project as sets of small interconnected libraries, binaries and tests. In contrast, with tools like Make, you have to describe individual files and compiler invocations.
* Multi-platform support: The same tool and the same `BUILD` files can be used to build software for different architectures, and even different platforms. At Google, we use Bazel to build everything from server applications running on systems in our data centers to client apps running on mobile phones.
* Reproducibility: In `BUILD` files, each library, test and binary must specify its direct dependencies completely. Bazel uses this dependency information to know what must be rebuilt when you make changes to a source file, and which tasks can run in parallel. This means that all builds are incremental and will always produce the same result.
* Scalable: Bazel can handle large builds; at Google, it is common for a server binary to have 100k source files, and builds where no files were changed take about \~200ms.
## Why doesn’t Google use...?
* Make, Ninja: These tools give very exact control over what commands get invoked to build files, but it’s up to the user to write rules that are correct.
* Users interact with Bazel on a higher level. For example, Bazel has built-in rules for “Java test”, “C++ binary”, and notions such as “target platform” and “host platform”. These rules have been battle tested to be foolproof.
* Ant and Maven: Ant and Maven are primarily geared toward Java, while Bazel handles multiple languages. Bazel encourages subdividing codebases in smaller reusable units, and can rebuild only ones that need rebuilding. This speeds up development when working with larger codebases.
* Gradle: Bazel configuration files are much more structured than Gradle’s, letting Bazel understand exactly what each action does. This allows for more parallelism and better reproducibility.
* Pants, Buck: Both tools were created and developed by ex-Googlers at Twitter and Foursquare, and Facebook respectively. They have been modeled after Bazel, but their feature sets are different, so they aren’t viable alternatives for us.
## Where did Bazel come from?
Bazel is a flavor of the tool that Google uses to build its server software internally. It has expanded to build other software as well, like mobile apps (iOS, Android) that connect to our servers.
## Did you rewrite your internal tool as open-source? Is it a fork?
Bazel shares most of its code with the internal tool and its rules are used for millions of builds every day.
## Why did Google build Bazel?
A long time ago, Google built its software using large, generated Makefiles. These led to slow and unreliable builds, which began to interfere with our developers’ productivity and the company’s agility. Bazel was a way to solve these problems.
## Does Bazel require a build cluster?
Bazel runs build operations locally by default. However, Bazel can also connect to a build cluster for even faster builds and tests. See our documentation on [remote execution and caching](/remote/rbe) and [remote caching](/remote/caching) for further details.
## How does the Google development process work?
For our server code base, we use the following development workflow:
* All our server code is in a single, gigantic version control system.
* Everybody builds their software with Bazel.
* Different teams own different parts of the source tree, and make their components available as `BUILD` targets.
* Branching is primarily used for managing releases, so everybody develops their software at the head revision.
Bazel is a cornerstone of this philosophy: since Bazel requires all dependencies to be fully specified, we can predict which programs and tests are affected by a change, and vet them before submission.
More background on the development process at Google can be found on the [eng tools blog](http://google-engtools.blogspot.com/).
## Why did you open up Bazel?
Building software should be fun and easy. Slow and unpredictable builds take the fun out of programming.
## Why would I want to use Bazel?
* Bazel may give you faster build times because it can recompile only the files that need to be recompiled. Similarly, it can skip re-running tests that it knows haven’t changed.
* Bazel produces deterministic results. This eliminates skew between incremental and clean builds, laptop and CI system, etc.
* Bazel can build different client and server apps with the same tool from the same workspace. For example, you can change a client/server protocol in a single commit, and test that the updated mobile app works with the updated server, building both with the same tool, reaping all the aforementioned benefits of Bazel.
## Can I see examples?
Yes; see a [simple example](https://github.com/bazelbuild/bazel/blob/master/examples/cpp/BUILD)
or read the [Bazel source code](https://github.com/bazelbuild/bazel/blob/master/src/BUILD) for a more complex example.
## What is Bazel best at?
Bazel shines at building and testing projects with the following properties:
* Projects with a large codebase
* Projects written in (multiple) compiled languages
* Projects that deploy on multiple platforms
* Projects that have extensive tests
## Where can I run Bazel?
Bazel runs on Linux, macOS (OS X), and Windows.
Porting to other UNIX platforms should be relatively easy, as long as a JDK is available for the platform.
## What should I not use Bazel for?
* Bazel tries to be smart about caching. This means that it is not good for running build operations whose outputs should not be cached. For example, the following steps should not be run from Bazel:
* A compilation step that fetches data from the internet.
* A test step that connects to the QA instance of your site.
* A deployment step that changes your site’s cloud configuration.
* If your build consists of a few long, sequential steps, Bazel may not be able to help much. You’ll get more speed by breaking long steps into smaller, discrete targets that Bazel can run in parallel.
## How stable is Bazel’s feature set?
The core features (C++, Java, and shell rules) have extensive use inside Google, so they are thoroughly tested and have very little churn. Similarly, we test new versions of Bazel across hundreds of thousands of targets every day to find regressions, and we release new versions multiple times every month.
In short, except for features marked as experimental, Bazel should Just Work. Changes to non-experimental rules will be backward compatible. A more detailed list of feature support statuses can be found in our [support document](/contribute/support).
## How stable is Bazel as a binary?
Inside Google, we make sure that Bazel crashes are very rare. This should also hold for our open source codebase.
## How can I start using Bazel?
See [Getting Started](/start/).
## Doesn’t Docker solve the reproducibility problems?
With Docker you can easily create sandboxes with fixed OS releases, for example, Ubuntu 12.04, Fedora 21. This solves the problem of reproducibility for the system environment – that is, “which version of /usr/bin/c++ do I need?”
Docker does not address reproducibility with regard to changes in the source code. Running Make with an imperfectly written Makefile inside a Docker container can still yield unpredictable results.
Inside Google, we check tools into source control for reproducibility. In this way, we can vet changes to tools (“upgrade GCC to 4.6.1”) with the same mechanism as changes to base libraries (“fix bounds check in OpenSSL”).
## Can I build binaries for deployment on Docker?
With Bazel, you can build standalone, statically linked binaries in C/C++, and self-contained jar files for Java. These run with few dependencies on normal UNIX systems, and as such should be simple to install inside a Docker container.
Bazel has conventions for structuring more complex programs, for example, a Java program that consumes a set of data files, or runs another program as subprocess. It is possible to package up such environments as standalone archives, so they can be deployed on different systems, including Docker images.
## Can I build Docker images with Bazel?
Yes, you can use our [Docker rules](https://github.com/bazelbuild/rules_docker) to build reproducible Docker images.
## Will Bazel make my builds reproducible automatically?
For Java and C++ binaries, yes, assuming you do not change the toolchain. If you have build steps that involve custom recipes (for example, executing binaries through a shell script inside a rule), you will need to take some extra care:
* Do not use dependencies that were not declared. Sandboxed execution (–spawn\_strategy=sandboxed, only on Linux) can help find undeclared dependencies.
* Avoid storing timestamps and user-IDs in generated files. ZIP files and other archives are especially prone to this.
* Avoid connecting to the network. Sandboxed execution can help here too.
* Avoid processes that use random numbers, in particular, dictionary traversal is randomized in many programming languages.
## Do you have binary releases?
Yes, you can find the latest [release binaries](https://github.com/bazelbuild/bazel/releases/latest) and review our [release policy](/release/)
## I use Eclipse/IntelliJ/XCode. How does Bazel interoperate with IDEs?
For IntelliJ, check out the [IntelliJ with Bazel plugin](https://ij.bazel.build/).
For XCode, check out [Tulsi](http://tulsi.bazel.build/).
For Eclipse, check out [E4B plugin](https://github.com/bazelbuild/e4b).
For other IDEs, check out the [blog post](https://blog.bazel.build/2016/06/10/ide-support.html) on how these plugins work.
## I use Jenkins/CircleCI/TravisCI. How does Bazel interoperate with CI systems?
Bazel returns a non-zero exit code if the build or test invocation fails, and this should be enough for basic CI integration. Since Bazel does not need clean builds for correctness, the CI system should not be configured to clean before starting a build/test run.
Further details on exit codes are in the [Scripts guide](/run/scripts#exit-codes).
## Can I use Bazel for my INSERT LANGUAGE HERE project?
Bazel is extensible. Anyone can add support for new languages. Many languages are supported: see the [build encyclopedia](/reference/be/overview) for a list of recommendations and [awesomebazel.com](https://awesomebazel.com/) for a more comprehensive list.
If you would like to develop extensions or learn how they work, see the documentation for [extending Bazel](/extending/concepts).
## Can I contribute to the Bazel code base?
See our [contribution guidelines](/contribute/).
## Why isn’t all development done in the open?
We still have to refactor the interfaces between the public code in Bazel and our internal extensions frequently. This makes it hard to do much development in the open.
## Are you done open sourcing Bazel?
Open sourcing Bazel is a work-in-progress. In particular, we’re still working on open sourcing:
* Many of our unit and integration tests (which should make contributing patches easier).
* Full IDE integration.
Beyond code, we’d like to eventually have all code reviews, bug tracking, and design decisions happen publicly, with the Bazel community involved. We are not there yet, so some changes will simply appear in the Bazel repository without clear explanation. Despite this lack of transparency, we want to support external developers and collaborate. Thus, we are opening up the code, even though some of the development is still happening internal to Google. Please let us know if anything seems unclear or unjustified as we transition to an open model.
## Are there parts of Bazel that will never be open sourced?
Yes, some of the code base either integrates with Google-specific technology or we have been looking for an excuse to get rid of (or is some combination of the two). These parts of the code base are not available on GitHub and probably never will be.
## How do I contact the team?
We are reachable at [bazel-discuss@googlegroups.com](mailto:bazel-discuss@googlegroups.com).
## Where do I report bugs?
Open an issue [on GitHub](https://github.com/bazelbuild/bazel/issues).
## What’s up with the word “Blaze” in the codebase?
This is an internal name for the tool. Please refer to Blaze as Bazel.
## Why do other Google projects (Android, Chrome) use other build tools?
Until the first (Alpha) release, Bazel was not available externally, so open source projects such as Chromium and Android could not use it. In addition, the original lack of Windows support was a problem for building Windows applications, such as Chrome. Since the project has matured and become more stable, the [Android Open Source Project](https://source.android.com/) is in the process of migrating to Bazel.
## How do you pronounce “Bazel”?
The same way as “basil” (the herb) in US English: “BAY-zel”. It rhymes with “hazel”. IPA: /ˈbeɪzˌəl/
# Intro to Bazel
Source: https://bazel.build/about/intro
Bazel is an open-source build and test tool similar to Make, Maven, and Gradle.
It uses a human-readable, high-level build language. Bazel supports projects in
multiple languages and builds outputs for multiple platforms. Bazel supports
large codebases across multiple repositories, and large numbers of users.
## Benefits
Bazel offers the following advantages:
* **High-level build language.** Bazel uses an abstract, human-readable
language to describe the build properties of your project at a high
semantical level. Unlike other tools, Bazel operates on the *concepts*
of libraries, binaries, scripts, and data sets, shielding you from the
complexity of writing individual calls to tools such as compilers and
linkers.
* **Bazel is fast and reliable.** Bazel caches all previously done work and
tracks changes to both file content and build commands. This way, Bazel
knows when something needs to be rebuilt, and rebuilds only that. To further
speed up your builds, you can set up your project to build in a highly
parallel and incremental fashion.
* **Bazel is multi-platform.** Bazel runs on Linux, macOS, and Windows. Bazel
can build binaries and deployable packages for multiple platforms, including
desktop, server, and mobile, from the same project.
* **Bazel scales.** Bazel maintains agility while handling builds with 100k+
source files. It works with multiple repositories and user bases in the tens
of thousands.
* **Bazel is extensible.** Many [languages](/rules) are
supported, and you can extend Bazel to support any other language or
framework.
## Using Bazel
To build or test a project with Bazel, you typically do the following:
1. **Set up Bazel.** Download and [install Bazel](/install).
2. **Set up a project [workspace](/concepts/build-ref#workspaces)**, which is a
directory where Bazel looks for build inputs and `BUILD` files, and where it
stores build outputs.
3. **Write a `BUILD` file**, which tells Bazel what to build and how to
build it.
You write your `BUILD` file by declaring build targets using
[Starlark](/rules/language), a domain-specific language. (See example
[here](https://github.com/bazelbuild/bazel/blob/master/examples/cpp/BUILD).)
A build target specifies a set of input artifacts that Bazel will build plus
their dependencies, the build rule Bazel will use to build it, and options
that configure the build rule.
A build rule specifies the build tools Bazel will use, such as compilers and
linkers, and their configurations. Bazel ships with a number of build rules
covering the most common artifact types in the supported languages on
supported platforms.
4. **Run Bazel** from the [command line](/reference/command-line-reference). Bazel
places your outputs within the workspace.
In addition to building, you can also use Bazel to run
[tests](/reference/test-encyclopedia) and [query](/query/guide) the build
to trace dependencies in your code.
## Bazel build process
When running a build or a test, Bazel does the following:
1. **Loads** the `BUILD` files relevant to the target.
2. **Analyzes** the inputs and their
[dependencies](/concepts/dependencies), applies the specified build
rules, and produces an [action](/extending/concepts#evaluation-model)
graph.
3. **Executes** the build actions on the inputs until the final build outputs
are produced.
Since all previous build work is cached, Bazel can identify and reuse cached
artifacts and only rebuild or retest what's changed. To further enforce
correctness, you can set up Bazel to run builds and tests
[hermetically](/basics/hermeticity) through sandboxing, minimizing skew
and maximizing [reproducibility](/run/build#correct-incremental-rebuilds).
### Action graph
The action graph represents the build artifacts, the relationships between them,
and the build actions that Bazel will perform. Thanks to this graph, Bazel can
[track](/run/build#build-consistency) changes to
file content as well as changes to actions, such as build or test commands, and
know what build work has previously been done. The graph also enables you to
easily [trace dependencies](/query/guide) in your code.
## Getting started tutorials
To get started with Bazel, see [Getting Started](/start/) or jump
directly to the Bazel tutorials:
* [Tutorial: Build a C++ Project](/start/cpp)
* [Tutorial: Build a Java Project](/start/java)
* [Tutorial: Build an Android Application](/start/android-app)
* [Tutorial: Build an iOS Application](/start/ios-app)
# Bazel Vision
Source: https://bazel.build/about/vision
Any software developer can efficiently build, test, and package
any project, of any size or complexity, with tooling that's easy to adopt and
extend.
* **Engineers can take build fundamentals for granted.** Software developers
focus on the creative process of authoring code because the mechanical
process of build and test is solved. When customizing the build system to
support new languages or unique organizational needs, users focus on the
aspects of extensibility that are unique to their use case, without having
to reinvent the basic plumbing.
* **Engineers can easily contribute to any project.** A developer who wants to
start working on a new project can simply clone the project and run the
build. There's no need for local configuration - it just works. With
cross-platform remote execution, they can work on any machine anywhere and
fully test their changes against all platforms the project targets.
Engineers can quickly configure the build for a new project or incrementally
migrate an existing build.
* **Projects can scale to any size codebase, any size team.** Fast,
incremental testing allows teams to fully validate every change before it is
committed. This remains true even as repos grow, projects span multiple
repos, and multiple languages are introduced. Infrastructure does not force
developers to trade test coverage for build speed.
**We believe Bazel has the potential to fulfill this vision.**
Bazel was built from the ground up to enable builds that are reproducible (a
given set of inputs will always produce the same outputs) and portable (a build
can be run on any machine without affecting the output).
These characteristics support safe incrementality (rebuilding only changed
inputs doesn't introduce the risk of corruption) and distributability (build
actions are isolated and can be offloaded). By minimizing the work needed to do
a correct build and parallelizing that work across multiple cores and remote
systems, Bazel can make any build fast.
Bazel's abstraction layer — instructions specific to languages, platforms, and
toolchains implemented in a simple extensibility language — allows it to be
easily applied to any context.
## Bazel core competencies
1. Bazel supports **multi-language, multi-platform** builds and tests. You can
run a single command to build and test your entire source tree, no matter
which combination of languages and platforms you target.
2. Bazel builds are **fast and correct**. Every build and test run is
incremental, on your developers' machines and on CI.
3. Bazel provides a **uniform, extensible language** to define builds for any
language or platform.
4. Bazel allows your builds **to scale** by connecting to remote execution and
caching services.
5. Bazel works across **all major development platforms** (Linux, MacOS, and
Windows).
6. We accept that adopting Bazel requires effort, but **gradual adoption** is
possible. Bazel interfaces with de-facto standard tools for a given
language/platform.
## Serving language communities
Software engineering evolves in the context of language communities — typically,
self-organizing groups of people who use common tools and practices.
To be of use to members of a language community, high-quality Bazel rules must be
available that integrate with the workflows and conventions of that community.
Bazel is committed to be extensible and open, and to support good rulesets for
any language.
### Requirements of a good ruleset
1. The rules need to support efficient **building and testing** for the
language, including code coverage.
2. The rules need to **interface with a widely-used "package manager"** for the
language (such as Maven for Java), and support incremental migration paths
from other widely-used build systems.
3. The rules need to be **extensible and interoperable**, following
["Bazel sandwich"](https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2016-08-04-extensibility-for-native-rules.md)
principles.
4. The rules need to be **remote-execution ready**. In practice, this means
**configurable using the [toolchains](/extending/toolchains) mechanism**.
5. The rules (and Bazel) need to interface with a **widely-used IDE** for the
language, if there is one.
6. The rules need to have **thorough, usable documentation,** with introductory
material for new users, comprehensive docs for expert users.
Each of these items is essential and only together do they deliver on Bazel's
competencies for their particular ecosystem.
They are also, by and large, sufficient - once all are fulfilled, Bazel fully
delivers its value to members of that language community.
# Why Bazel?
Source: https://bazel.build/about/why
Bazel is a [fast](#fast), [correct](#correct), and [extensible](#extensible)
build tool with [integrated testing](#integrated-testing) that supports multiple
[languages](#multi-language), [repositories](#multi-repository), and
[platforms](#multi-platform) in an industry-leading [ecosystem](#ecosystem).
## Bazel is fast
Bazel knows exactly what input files each build command needs, avoiding
unnecessary work by re-running only when the set of input files have
changed between each build.
It runs build commands with as much parallelism as possible, either within the
same computer or on [remote build nodes](/remote/rbe). If the structure of build
allows for it, it can run thousands of build or test commands at the same time.
This is supported by multiple caching layers, in memory, on disk and on the
remote build farm, if available. At Google, we routinely achieve cache hit rates
north of 99%.
## Bazel is correct
Bazel ensures that your binaries are built *only* from your own
source code. Bazel actions run in individual sandboxes and Bazel tracks
every input file of the build, only and always re-running build
commands when it needs to. This keeps your binaries up-to-date so that the
[same source code always results in the same binary](/basics/hermeticity), bit
by bit.
Say goodbye to endless `make clean` invocations and to chasing phantom bugs
that were in fact resolved in source code that never got built.
## Bazel is extensible
Harness the full power of Bazel by writing your own rules and macros to
customize Bazel for your specific needs across a wide range of projects.
Bazel rules are written in [Starlark](/rules/language), our
in-house programming language that's a subset of Python. Starlark makes
rule-writing accessible to most developers, while also creating rules that can
be used across the ecosystem.
## Integrated testing
Bazel's [integrated test runner](/docs/user-manual#running-tests)
knows and runs only those tests needing to be re-run, using remote execution
(if available) to run them in parallel. Detect flakes early by using remote
execution to quickly run a test thousands of times.
Bazel [provides facilities](/remote/bep) to upload test results to a central
location, thereby facilitating efficient communication of test outcomes, be it
on CI or by individual developers.
## Multi-language support
Bazel supports many common programming languages including C++, Java,
Kotlin, Python, Go, and Rust. You can build multiple binaries (for example,
backend, web UI and mobile app) in the same Bazel invocation without being
constrained to one language's idiomatic build tool.
## Multi-repository support
Bazel can [gather source code from multiple locations](/external/overview): you
don't need to vendor your dependencies (but you can!), you can instead point
Bazel to the location of your source code or prebuilt artifacts (e.g. a git
repository or Maven Central), and it takes care of the rest.
## Multi-platform support
Bazel can simultaneously build projects for multiple platforms including Linux,
macOS, Windows, and Android. It also provides powerful
[cross-compilation capabilities](/extending/platforms) to build code for one
platform while running the build on another.
## Wide ecosystem
[Industry leaders](/community/users) love Bazel, building a large
community of developers who use and contribute to Bazel. Find a tools, services
and documentation, including [consulting and SaaS offerings](/community/experts)
Bazel can use. Explore extensions like support for programming languages in
our [open source software repositories](/rules).
# Breaking down build performance
Source: https://bazel.build/advanced/performance/build-performance-breakdown
Bazel is complex and does a lot of different things over the course of a build,
some of which can have an impact on build performance. This page attempts to map
some of these Bazel concepts to their implications on build performance. While
not extensive, we have included some examples of how to detect build performance
issues through [extracting metrics](/configure/build-performance-metrics)
and what you can do to fix them. With this, we hope you can apply these concepts
when investigating build performance regressions.
### Clean vs Incremental builds
A clean build is one that builds everything from scratch, while an incremental
build reuses some already completed work.
We suggest looking at clean and incremental builds separately, especially when
you are collecting / aggregating metrics that are dependent on the state of
Bazel’s caches (for example
[build request size metrics](#deterministic-build-metrics-as-a-proxy-for-build-performance)
). They also represent two different user experiences. As compared to starting
a clean build from scratch (which takes longer due to a cold cache), incremental
builds happen far more frequently as developers iterate on code (typically
faster since the cache is usually already warm).
You can use the `CumulativeMetrics.num_analyses` field in the BEP to classify
builds. If `num_analyses <= 1`, it is a clean build; otherwise, we can broadly
categorize it to likely be an incremental build - the user could have switched
to different flags or different targets causing an effectively clean build. Any
more rigorous definition of incrementality will likely have to come in the form
of a heuristic, for example looking at the number of packages loaded
(`PackageMetrics.packages_loaded`).
### Deterministic build metrics as a proxy for build performance
Measuring build performance can be difficult due to the non-deterministic nature
of certain metrics (for example Bazel’s CPU time or queue times on a remote
cluster). As such, it can be useful to use deterministic metrics as a proxy for
the amount of work done by Bazel, which in turn affects its performance.
The size of a build request can have a significant implication on build
performance. A larger build could represent more work in analyzing and
constructing the build graphs. Organic growth of builds comes naturally with
development, as more dependencies are added/created, and thus grow in complexity
and become more expensive to build.
We can slice this problem into the various build phases, and use the following
metrics as proxy metrics for work done at each phase:
1. `PackageMetrics.packages_loaded`: the number of packages successfully loaded.
A regression here represents more work that needs to be done to read and parse
each additional BUILD file in the loading phase.
* This is often due to the addition of dependencies and having to load their
transitive closure.
* Use [query](/query/quickstart) / [cquery](/query/cquery) to find
where new dependencies might have been added.
2. `TargetMetrics.targets_configured`: representing the number of targets and
aspects configured in the build. A regression represents more work in
constructing and traversing the configured target graph.
* This is often due to the addition of dependencies and having to construct
the graph of their transitive closure.
* Use [cquery](/query/cquery) to find where new
dependencies might have been added.
3. `ActionSummary.actions_created`: represents the actions created in the build,
and a regression represents more work in constructing the action graph. Note
that this also includes unused actions that might not have been executed.
* Use [aquery](/query/aquery) for debugging regressions;
we suggest starting with
[`--output=summary`](/reference/command-line-reference#flag--output)
before further drilling down with
[`--skyframe_state`](/reference/command-line-reference#flag--skyframe_state).
4. `ActionSummary.actions_executed`: the number of actions executed, a
regression directly represents more work in executing these actions.
* The [BEP](/remote/bep) writes out the action statistics
`ActionData` that shows the most executed action types. By default, it
collects the top 20 action types, but you can pass in the
[`--experimental_record_metrics_for_all_mnemonics`](/reference/command-line-reference#flag--experimental_record_metrics_for_all_mnemonics)
to collect this data for all action types that were executed.
* This should help you to figure out what kind of actions were executed
(additionally).
5. `BuildGraphSummary.outputArtifactCount`: the number of artifacts created by
the executed actions.
* If the number of actions executed did not increase, then it is likely that
a rule implementation was changed.
These metrics are all affected by the state of the local cache, hence you will
want to ensure that the builds you extract these metrics from are
**clean builds**.
We have noted that a regression in any of these metrics can be accompanied by
regressions in wall time, cpu time and memory usage.
### Usage of local resources
Bazel consumes a variety of resources on your local machine (both for analyzing
the build graph and driving the execution, and for running local actions), this
can affect the performance / availability of your machine in performing the
build, and also other tasks.
#### Time spent
Perhaps the metrics most susceptible to noise (and can vary greatly from build
to build) is time; in particular - wall time, cpu time and system time. You can
use [bazel-bench](https://github.com/bazelbuild/bazel-bench) to get
a benchmark for these metrics, and with a sufficient number of `--runs`, you can
increase the statistical significance of your measurement.
* **Wall time** is the real world time elapsed.
* If *only* wall time regresses, we suggest collecting a
[JSON trace profile](/advanced/performance/json-trace-profile) and looking
for differences. Otherwise, it would likely be more efficient to
investigate other regressed metrics as they could have affected the wall
time.
* **CPU time** is the time spent by the CPU executing user code.
* If the CPU time regresses across two project commits, we suggest collecting
a Starlark CPU profile. You should probably also use `--nobuild` to
restrict the build to the analysis phase since that is where most of the
CPU heavy work is done.
* System time is the time spent by the CPU in the kernel.
* If system time regresses, it is mostly correlated with I/O when Bazel reads
files from your file system.
#### System-wide load profiling
Using the
[`--experimental_collect_load_average_in_profiler`](https://github.com/bazelbuild/bazel/blob/6.0.0/src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java#L306-L312)
flag introduced in Bazel 6.0, the
[JSON trace profiler](/advanced/performance/json-trace-profile) collects the
system load average during the invocation.
**Figure 1.** Profile that includes system load average.
A high load during a Bazel invocation can be an indication that Bazel schedules
too many local actions in parallel for your machine. You might want to look into
adjusting
[`--local_cpu_resources`](/reference/command-line-reference#flag--local_cpu_resources)
and [`--local_ram_resources`](/reference/command-line-reference#flag--local_ram_resources),
especially in container environments (at least until
[#16512](https://github.com/bazelbuild/bazel/pull/16512) is merged).
#### Monitoring Bazel memory usage
There are two main sources to get Bazel’s memory usage, Bazel `info` and the
[BEP](/remote/bep).
* `bazel info used-heap-size-after-gc`: The amount of used memory in bytes after
a call to `System.gc()`.
* [Bazel bench](https://github.com/bazelbuild/bazel-bench)
provides benchmarks for this metric as well.
* Additionally, there are `peak-heap-size`, `max-heap-size`, `used-heap-size`
and `committed-heap-size` (see
[documentation](/docs/user-manual#configuration-independent-data)), but are
less relevant.
* [BEP](/remote/bep)’s
`MemoryMetrics.peak_post_gc_heap_size`: Size of the peak JVM heap size in
bytes post GC (requires setting
[`--memory_profile`](/reference/command-line-reference#flag--memory_profile)
that attempts to force a full GC).
A regression in memory usage is usually a result of a regression in
[build request size metrics](#deterministic_build_metrics_as_a_proxy_for_build_performance),
which are often due to addition of dependencies or a change in the rule
implementation.
To analyze Bazel’s memory footprint on a more granular level, we recommend using
the [built-in memory profiler](/rules/performance#memory-profiling)
for rules.
#### Memory profiling of persistent workers
While [persistent workers](/remote/persistent) can help to speed up builds
significantly (especially for interpreted languages) their memory footprint can
be problematic. Bazel collects metrics on its workers, in particular, the
`WorkerMetrics.WorkerStats.worker_memory_in_kb` field tells how much memory
workers use (by mnemonic).
The [JSON trace profiler](/advanced/performance/json-trace-profile) also
collects persistent worker memory usage during the invocation by passing in the
[`--experimental_collect_system_network_usage`](https://github.com/bazelbuild/bazel/blob/6.0.0/src/main/java/com/google/devtools/build/lib/runtime/CommonCommandOptions.java#L314-L320)
flag (new in Bazel 6.0).
**Figure 2.** Profile that includes workers memory usage.
Lowering the value of
[`--worker_max_instances`](/reference/command-line-reference#flag--worker_max_instances)
(default 4) might help to reduce
the amount of memory used by persistent workers. We are actively working on
making Bazel’s resource manager and scheduler smarter so that such fine tuning
will be required less often in the future.
### Monitoring network traffic for remote builds
In remote execution, Bazel downloads artifacts that were built as a result of
executing actions. As such, your network bandwidth can affect the performance
of your build.
If you are using remote execution for your builds, you might want to consider
monitoring the network traffic during the invocation using the
`NetworkMetrics.SystemNetworkStats` proto from the [BEP](/remote/bep)
(requires passing `--experimental_collect_system_network_usage`).
Furthermore, [JSON trace profiles](/advanced/performance/json-trace-profile)
allow you to view system-wide network usage throughout the course of the build
by passing the `--experimental_collect_system_network_usage` flag (new in Bazel
6.0).
**Figure 3.** Profile that includes system-wide network usage.
A high but rather flat network usage when using remote execution might indicate
that network is the bottleneck in your build; if you are not using it already,
consider turning on Build without the Bytes by passing
[`--remote_download_minimal`](/reference/command-line-reference#flag--remote_download_minimal).
This will speed up your builds by avoiding the download of unnecessary intermediate artifacts.
Another option is to configure a local
[disk cache](/reference/command-line-reference#flag--disk_cache) to save on
download bandwidth.
# Extracting build performance metrics
Source: https://bazel.build/advanced/performance/build-performance-metrics
Probably every Bazel user has experienced builds that were slow or slower than
anticipated. Improving the performance of individual builds has particular value
for targets with significant impact, such as:
1. Core developer targets that are frequently iterated on and (re)built.
2. Common libraries widely depended upon by other targets.
3. A representative target from a class of targets (e.g. custom rules),
diagnosing and fixing issues in one build might help to resolve issues at the
larger scale.
An important step to improving the performance of builds is to understand where
resources are spent. This page lists different metrics you can collect.
[Breaking down build performance](/configure/build-performance-breakdown) showcases
how you can use these metrics to detect and fix build performance issues.
There are a few main ways to extract metrics from your Bazel builds, namely:
## Build Event Protocol (BEP)
Bazel outputs a variety of protocol buffers
[`build_event_stream.proto`](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto)
through the [Build Event Protocol (BEP)](/remote/bep), which
can be aggregated by a backend specified by you. Depending on your use cases,
you might decide to aggregate the metrics in various ways, but here we will go
over some concepts and proto fields that would be useful in general to consider.
## Bazel’s query / cquery / aquery commands
Bazel provides 3 different query modes ([query](/query/quickstart),
[cquery](/query/cquery) and [aquery](/query/aquery)) that allow users
to query the target graph, configured target graph and action graph
respectively. The query language provides a
[suite of functions](/query/language#functions) usable across the different
query modes, that allows you to customize your queries according to your needs.
## JSON Trace Profiles
For every build-like Bazel invocation, Bazel writes a trace profile in JSON
format. The [JSON trace profile](/advanced/performance/json-trace-profile) can
be very useful to quickly understand what Bazel spent time on during the
invocation.
## Execution Log
The [execution log](/remote/cache-remote) can help you to troubleshoot and fix
missing remote cache hits due to machine and environment differences or
non-deterministic actions. If you pass the flag
[`--experimental_execution_log_spawn_metrics`](/reference/command-line-reference#flag--experimental_execution_log_spawn_metrics)
(available from Bazel 5.2) it will also contain detailed spawn metrics, both for
locally and remotely executed actions. You can use these metrics for example to
make comparisons between local and remote machine performance or to find out
which part of the spawn execution is consistently slower than expected (for
example due to queuing).
## Execution Graph Log
While the JSON trace profile contains the critical path information, sometimes
you need additional information on the dependency graph of the executed actions.
Starting with Bazel 6.0, you can pass the flags
`--experimental_execution_graph_log` and
`--experimental_execution_graph_log_dep_type=all` to write out a log about the
executed actions and their inter-dependencies.
This information can be used to understand the drag that is added by a node on
the critical path. The drag is the amount of time that can potentially be saved
by removing a particular node from the execution graph.
The data helps you predict the impact of changes to the build and action graph
before you actually do them.
## Benchmarking with bazel-bench
[Bazel bench](https://github.com/bazelbuild/bazel-bench) is a
benchmarking tool for Git projects to benchmark build performance in the
following cases:
* **Project benchmark:** Benchmarking two git commits against each other at a
single Bazel version. Used to detect regressions in your build (often through
the addition of dependencies).
* **Bazel benchmark:** Benchmarking two versions of Bazel against each other at
a single git commit. Used to detect regressions within Bazel itself (if you
happen to maintain / fork Bazel).
Benchmarks monitor wall time, CPU time and system time and Bazel’s retained
heap size.
It is also recommended to run Bazel bench on dedicated, physical machines that
are not running other processes so as to reduce sources of variability.
# Optimize Iteration Speed
Source: https://bazel.build/advanced/performance/iteration-speed
This page describes how to optimize Bazel's build performance when running Bazel
repeatedly.
## Bazel's Runtime State
A Bazel invocation involves several interacting parts.
* The `bazel` command line interface (CLI) is the user-facing front-end tool
and receives commands from the user.
* The CLI tool starts a [*Bazel server*](https://bazel.build/run/client-server)
for each distinct [output base](https://bazel.build/remote/output-directories).
The Bazel server is generally persistent, but will shut down after some idle
time so as to not waste resources.
* The Bazel server performs the loading and analysis steps for a given command
(`build`, `run`, `cquery`, etc.), in which it constructs the necessary parts
of the build graph in memory. The resulting data structures are retained in
the Bazel server as part of the *analysis cache*.
* The Bazel server can also perform the action execution, or it can send
actions off for remote execution if it is set up to do so. The results of
action executions are also cached, namely in the *action cache* (or
*execution cache*, which may be either local or remote, and it may be shared
among Bazel servers).
* The result of the Bazel invocation is made available in the output tree.
## Running Bazel Iteratively
In a typical developer workflow, it is common to build (or run) a piece of code
repeatedly, often at a very high frequency (e.g. to resolve some compilation
error or investigate a failing test). In this situation, it is important that
repeated invocations of `bazel` have as little overhead as possible relative to
the underlying, repeated action (e.g. invoking a compiler, or executing a test).
With this in mind, we take another look at Bazel's runtime state:
The analysis cache is a critical piece of data. A significant amount of time can
be spent just on the loading and analysis phases of a cold run (i.e. a run just
after the Bazel server was started or when the analysis cache was discarded).
For a single, successful cold build (e.g. for a production release) this cost is
bearable, but for repeatedly building the same target it is important that this
cost be amortized and not repeated on each invocation.
The analysis cache is rather volatile. First off, it is part of the in-process
state of the Bazel server, so losing the server loses the cache. But the cache
is also *invalidated* very easily: for example, many `bazel` command line flags
cause the cache to be discarded. This is because many flags affect the build
graph (e.g. because of
[configurable attributes](https://bazel.build/configure/attributes)). Some flag
changes can also cause the Bazel server to be restarted (e.g. changing
[startup options](https://bazel.build/docs/user-manual#startup-options)).
A good execution cache is also valuable for build performance. An execution
cache can be kept locally
[on disk](https://bazel.build/remote/caching#disk-cache), or
[remotely](https://bazel.build/remote/caching). The cache can be shared among
Bazel servers, and indeed among developers.
## Avoid discarding the analysis cache
Bazel will print a warning if either the analysis cache was discarded or the
server was restarted. Either of these should be avoided during iterative use:
* Be mindful of changing `bazel` flags in the middle of an iterative
workflow. For example, mixing a `bazel build -c opt` with a `bazel cquery`
causes each command to discard the analysis cache of the other. In general,
try to use a fixed set of flags for the duration of a particular workflow.
* Losing the Bazel server loses the analysis cache. The Bazel server has a
[configurable](https://bazel.build/docs/user-manual#max-idle-secs) idle
time, after which it shuts down. You can configure this time via your
bazelrc file to suit your needs. The server also restarted when startup
flags change, so, again, avoid changing those flags if possible.
* Beware that the Bazel server is killed if you press
Ctrl-C repeatedly while Bazel is running. It is tempting to try to save time
by interrupting a running build that is no longer needed, but only press
Ctrl-C once to request a graceful end of the current invocation.
* If you want to use multiple sets of flags from the same workspace, you can
use multiple, distinct output bases, switched with the `--output_base`
flag. Each output base gets its own Bazel server.
To make this condition an error rather than a warning, you can use the
`--noallow_analysis_cache_discard` flag (introduced in Bazel 6.4.0)
# JSON Trace Profile
Source: https://bazel.build/advanced/performance/json-trace-profile
The JSON trace profile can be very useful to quickly understand what Bazel spent
time on during the invocation.
By default, for all build-like commands and query, Bazel writes a profile into
the output base named `command-$INVOCATION_ID.profile.gz`, where
`$INVOCATION_ID` is the invocation identifier of the command. Bazel also creates
a symlink called `command.profile.gz` in the output base that points the profile
of the latest command. You can configure whether a profile is written with the
[`--generate_json_trace_profile`](/reference/command-line-reference#flag--generate_json_trace_profile)
flag, and the location it is written to with the
[`--profile`](/docs/user-manual#profile) flag. Locations ending with `.gz` are
compressed with GZIP. Bazel keeps the last 5 profiles, configurable by
[`--profiles_to_retain`](/reference/command-line-reference#flag--generate_json_trace_profile),
in the output base by default for post-build analysis. Explicitly passing a
profile path with `--profile` disables automatic garbage collection.
## Tools
You can load this profile into `chrome://tracing` or analyze and
post-process it with other tools.
### `chrome://tracing`
To visualize the profile, open `chrome://tracing` in a Chrome browser tab,
click "Load" and pick the (potentially compressed) profile file. For more
detailed results, click the boxes in the lower left corner.
Example profile:
**Figure 1.** Example profile.
You can use these keyboard controls to navigate:
* Press `1` for "select" mode. In this mode, you can select
particular boxes to inspect the event details (see lower left corner).
Select multiple events to get a summary and aggregated statistics.
* Press `2` for "pan" mode. Then drag the mouse to move the view. You
can also use `a`/`d` to move left/right.
* Press `3` for "zoom" mode. Then drag the mouse to zoom. You can
also use `w`/`s` to zoom in/out.
* Press `4` for "timing" mode where you can measure the distance
between two events.
* Press `?` to learn about all controls.
### Bazel Invocation Analyzer
The open-source
[Bazel Invocation Analyzer](https://github.com/EngFlow/bazel_invocation_analyzer)
consumes a profile format and prints suggestions on how to improve
the build’s performance. This analysis can be performed using its CLI or on
[https://analyzer.engflow.com](https://analyzer.engflow.com).
### `jq`
`jq` is like `sed` for JSON data. An example usage of `jq` to extract all
durations of the sandbox creation step in local action execution:
```
$ zcat $(../bazel-6.0.0rc1-linux-x86_64 info output_base)/command.profile.gz | jq '.traceEvents | .[] | select(.name == "sandbox.createFileSystem") | .dur'
6378
7247
11850
13756
6555
7445
8487
15520
[...]
```
## Profile information
The profile contains multiple rows. Usually the bulk of rows represent Bazel
threads and their corresponding events, but some special rows are also included.
The special rows included depend on the version of Bazel invoked when the
profile was created, and may be customized by different flags.
Figure 1 shows a profile created with Bazel v5.3.1 and includes these rows:
* `action count`: Displays how many concurrent actions were in flight. Click
on it to see the actual value. Should go up to the value of
[`--jobs`](/reference/command-line-reference#flag--jobs) in clean
builds.
* `CPU usage (Bazel)`: For each second of the build, displays the amount of
CPU that was used by Bazel (a value of 1 equals one core being 100% busy).
* `Critical Path`: Displays one block for each action on the critical path.
* `Main Thread`: Bazel’s main thread. Useful to get a high-level picture of
what Bazel is doing, for example "Launch Blaze", "evaluateTargetPatterns",
and "runAnalysisPhase".
* `Garbage Collector`: Displays minor and major Garbage Collection (GC)
pauses.
## Common performance issues
When analyzing performance profiles, look for:
* Slower than expected analysis phase (`runAnalysisPhase`), especially on
incremental builds. This can be a sign of a poor rule implementation, for
example one that flattens depsets. Package loading can be slow by an
excessive amount of targets, complex macros or recursive globs.
* Individual slow actions, especially those on the critical path. It might be
possible to split large actions into multiple smaller actions or reduce the
set of (transitive) dependencies to speed them up. Also check for an unusual
high non-`PROCESS_TIME` (such as `REMOTE_SETUP` or `FETCH`).
* Bottlenecks, that is a small number of threads is busy while all others are
idling / waiting for the result (see around 22s and 29s in Figure 1).
Optimizing this will most likely require touching the rule implementations
or Bazel itself to introduce more parallelism. This can also happen when
there is an unusual amount of GC.
## Profile file format
The top-level object contains metadata (`otherData`) and the actual tracing data
(`traceEvents`). The metadata contains extra info, for example the invocation ID
and date of the Bazel invocation.
Example:
```json theme={null}
{
"otherData": {
"build_id": "101bff9a-7243-4c1a-8503-9dc6ae4c3b05",
"date": "Wed Oct 26 08:22:35 CEST 2022",
"profile_finish_ts": "1677666095162000",
"output_base": "/usr/local/google/_bazel_johndoe/573d4be77eaa72b91a3dfaa497bf8cd0"
},
"traceEvents": [
{"name":"thread_name","ph":"M","pid":1,"tid":0,"args":{"name":"Critical Path"}},
...
{"cat":"build phase marker","name":"Launch Blaze","ph":"X","ts":-1306000,"dur":1306000,"pid":1,"tid":21},
...
{"cat":"package creation","name":"foo","ph":"X","ts":2685358,"dur":784,"pid":1,"tid":246},
...
{"name":"thread_name","ph":"M","pid":1,"tid":11,"args":{"name":"Garbage Collector"}},
{"cat":"gc notification","name":"minor GC","ph":"X","ts":825986,"dur":11000,"pid":1,"tid":11},
...
{"cat":"action processing","name":"Compiling foo/bar.c","ph":"X","ts":54413389,"dur":357594,"pid":1,"args":{"mnemonic":"CppCompile"},"tid":341},
]
}
```
Timestamps (`ts`) and durations (`dur`) in the trace events are given in
microseconds. The category (`cat`) is one of enum values of `ProfilerTask`.
Note that some events are merged together if they are very short and close to
each other; pass
[`--noslim_profile`](/reference/command-line-reference#flag--slim_profile)
if you would like to prevent event merging.
See also the
[Chrome Trace Event Format Specification](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview).
# Optimize Memory
Source: https://bazel.build/advanced/performance/memory
This page describes how to limit and reduce the memory Bazel uses.
## Running Bazel with Limited RAM
In certain situations, you may want Bazel to use minimal memory. You can set the
maximum heap via the startup flag
[`--host_jvm_args`](/docs/user-manual#host-jvm-args),
like `--host_jvm_args=-Xmx2g`.
### Trade incremental build speeds for memory
If your builds are too big, Bazel may throw an `OutOfMemoryError` (OOM) when
it doesn't have enough memory. You can make Bazel use less memory, at the cost
of slower incremental builds, by passing the following command flags:
[`--discard_analysis_cache`](/docs/user-manual#discard-analysis-cache),
[`--nokeep_state_after_build`](/reference/command-line-reference#flag--keep_state_after_build),
and
[`--notrack_incremental_state`](/reference/command-line-reference#flag--track_incremental_state).
These flags will minimize the memory that Bazel uses in a build, at the cost of
making future builds slower than a standard incremental build would be.
You can also pass any one of these flags individually:
* `--discard_analysis_cache` will reduce the memory used during execution (not
analysis). Incremental builds will not have to redo package loading, but will
have to redo analysis and execution (although the on-disk action cache can
prevent most re-execution).
* `--notrack_incremental_state` will not store any edges in Bazel's internal
dependency graph, so that it is unusable for incremental builds. The next build
will discard that data, but it is preserved until then, for internal debugging,
unless `--nokeep_state_after_build` is specified.
* `--nokeep_state_after_build` will discard all data after the build, so that
incremental builds have to build from scratch (except for the on-disk action
cache). Alone, it does not affect the high-water mark of the current build.
## Memory Profiling
Bazel comes with a built-in memory profiler that can help you check your rule’s
memory use. Read more about this process on the
[Memory Profiling section](/rules/performance#memory-profiling) of our
documentation on how to improve the performance of custom rules.
# Artifact-Based Build Systems
Source: https://bazel.build/basics/artifact-based-builds
This page covers artifact-based build systems and the philosophy behind their
creation. Bazel is an artifact-based build system. While task-based build
systems are good step above build scripts, they give too much power to
individual engineers by letting them define their own tasks.
Artifact-based build systems have a small number of tasks defined by the system
that engineers can configure in a limited way. Engineers still tell the system
**what** to build, but the build system determines **how** to build it. As with
task-based build systems, artifact-based build systems, such as Bazel, still
have buildfiles, but the contents of those buildfiles are very different. Rather
than being an imperative set of commands in a Turing-complete scripting language
describing how to produce an output, buildfiles in Bazel are a declarative
manifest describing a set of artifacts to build, their dependencies, and a
limited set of options that affect how they’re built. When engineers run `bazel`
on the command line, they specify a set of targets to build (the **what**), and
Bazel is responsible for configuring, running, and scheduling the compilation
steps (the **how**). Because the build system now has full control over what
tools to run when, it can make much stronger guarantees that allow it to be far
more efficient while still guaranteeing correctness.
## A functional perspective
It’s easy to make an analogy between artifact-based build systems and functional
programming. Traditional imperative programming languages (such as, Java, C, and
Python) specify lists of statements to be executed one after another, in the
same way that task-based build systems let programmers define a series of steps
to execute. Functional programming languages (such as, Haskell and ML), in
contrast, are structured more like a series of mathematical equations. In
functional languages, the programmer describes a computation to perform, but
leaves the details of when and exactly how that computation is executed to the
compiler.
This maps to the idea of declaring a manifest in an artifact-based build system
and letting the system figure out how to execute the build. Many problems can't
be easily expressed using functional programming, but the ones that do benefit
greatly from it: the language is often able to trivially parallelize such
programs and make strong guarantees about their correctness that would be
impossible in an imperative language. The easiest problems to express using
functional programming are the ones that simply involve transforming one piece
of data into another using a series of rules or functions. And that’s exactly
what a build system is: the whole system is effectively a mathematical function
that takes source files (and tools like the compiler) as inputs and produces
binaries as outputs. So, it’s not surprising that it works well to base a build
system around the tenets of functional programming.
## Understanding artifact-based build systems
Google's build system, Blaze, was the first artifact-based build system. Bazel
is the open-sourced version of Blaze.
Here’s what a buildfile (normally named `BUILD`) looks like in Bazel:
```python theme={null}
java_binary(
name = "MyBinary",
srcs = ["MyBinary.java"],
deps = [
":mylib",
],
)
java_library(
name = "mylib",
srcs = ["MyLibrary.java", "MyHelper.java"],
visibility = ["//java/com/example/myproduct:__subpackages__"],
deps = [
"//java/com/example/common",
"//java/com/example/myproduct/otherlib",
],
)
```
In Bazel, `BUILD` files define targets—the two types of targets here are
`java_binary` and `java_library`. Every target corresponds to an artifact that
can be created by the system: binary targets produce binaries that can be
executed directly, and library targets produce libraries that can be used by
binaries or other libraries. Every target has:
* `name`: how the target is referenced on the command line and by other
targets
* `srcs`: the source files to be compiled to create the artifact for the target
* `deps`: other targets that must be built before this target and linked into
it
Dependencies can either be within the same package (such as `MyBinary`’s
dependency on `:mylib`) or on a different package in the same source hierarchy
(such as `mylib`’s dependency on `//java/com/example/common`).
As with task-based build systems, you perform builds using Bazel’s command-line
tool. To build the `MyBinary` target, you run `bazel build :MyBinary`. After
entering that command for the first time in a clean repository, Bazel:
1. Parses every `BUILD` file in the workspace to create a graph of dependencies
among artifacts.
2. Uses the graph to determine the transitive dependencies of `MyBinary`; that
is, every target that `MyBinary` depends on and every target that those
targets depend on, recursively.
3. Builds each of those dependencies, in order. Bazel starts by building each
target that has no other dependencies and keeps track of which dependencies
still need to be built for each target. As soon as all of a target’s
dependencies are built, Bazel starts building that target. This process
continues until every one of `MyBinary`’s transitive dependencies have been
built.
4. Builds `MyBinary` to produce a final executable binary that links in all of
the dependencies that were built in step 3.
Fundamentally, it might not seem like what’s happening here is that much
different than what happened when using a task-based build system. Indeed, the
end result is the same binary, and the process for producing it involved
analyzing a bunch of steps to find dependencies among them, and then running
those steps in order. But there are critical differences. The first one appears
in step 3: because Bazel knows that each target only produces a Java library, it
knows that all it has to do is run the Java compiler rather than an arbitrary
user-defined script, so it knows that it’s safe to run these steps in parallel.
This can produce an order of magnitude performance improvement over building
targets one at a time on a multicore machine, and is only possible because the
artifact-based approach leaves the build system in charge of its own execution
strategy so that it can make stronger guarantees about parallelism.
The benefits extend beyond parallelism, though. The next thing that this
approach gives us becomes apparent when the developer types `bazel
build :MyBinary` a second time without making any changes: Bazel exits in less
than a second with a message saying that the target is up to date. This is
possible due to the functional programming paradigm we talked about
earlier—Bazel knows that each target is the result only of running a Java
compiler, and it knows that the output from the Java compiler depends only on
its inputs, so as long as the inputs haven’t changed, the output can be reused.
And this analysis works at every level; if `MyBinary.java` changes, Bazel knows
to rebuild `MyBinary` but reuse `mylib`. If a source file for
`//java/com/example/common` changes, Bazel knows to rebuild that library,
`mylib`, and `MyBinary`, but reuse `//java/com/example/myproduct/otherlib`.
Because Bazel knows about the properties of the tools it runs at every step,
it’s able to rebuild only the minimum set of artifacts each time while
guaranteeing that it won’t produce stale builds.
Reframing the build process in terms of artifacts rather than tasks is subtle
but powerful. By reducing the flexibility exposed to the programmer, the build
system can know more about what is being done at every step of the build. It can
use this knowledge to make the build far more efficient by parallelizing build
processes and reusing their outputs. But this is really just the first step, and
these building blocks of parallelism and reuse form the basis for a distributed
and highly scalable build system.
## Other nifty Bazel tricks
Artifact-based build systems fundamentally solve the problems with parallelism
and reuse that are inherent in task-based build systems. But there are still a
few problems that came up earlier that we haven’t addressed. Bazel has clever
ways of solving each of these, and we should discuss them before moving on.
### Tools as dependencies
One problem we ran into earlier was that builds depended on the tools installed
on our machine, and reproducing builds across systems could be difficult due to
different tool versions or locations. The problem becomes even more difficult
when your project uses languages that require different tools based on which
platform they’re being built on or compiled for (such as, Windows versus Linux),
and each of those platforms requires a slightly different set of tools to do the
same job.
Bazel solves the first part of this problem by treating tools as dependencies to
each target. Every `java_library` in the workspace implicitly depends on a Java
compiler, which defaults to a well-known compiler. Whenever Bazel builds a
`java_library`, it checks to make sure that the specified compiler is available
at a known location. Just like any other dependency, if the Java compiler
changes, every artifact that depends on it is rebuilt.
Bazel solves the second part of the problem, platform independence, by setting
[build configurations](/run/build#build-config-cross-compilation). Rather than
targets depending directly on their tools, they depend on types of configurations:
* **Host configuration**: building tools that run during the build
* **Target configuration**: building the binary you ultimately requested
### Extending the build system
Bazel comes with targets for several popular programming languages out of the
box, but engineers will always want to do more—part of the benefit of task-based
systems is their flexibility in supporting any kind of build process, and it
would be better not to give that up in an artifact-based build system.
Fortunately, Bazel allows its supported target types to be extended by
[adding custom rules](/extending/rules).
To define a rule in Bazel, the rule author declares the inputs that the rule
requires (in the form of attributes passed in the `BUILD` file) and the fixed
set of outputs that the rule produces. The author also defines the actions that
will be generated by that rule. Each action declares its inputs and outputs,
runs a particular executable or writes a particular string to a file, and can be
connected to other actions via its inputs and outputs. This means that actions
are the lowest-level composable unit in the build system—an action can do
whatever it wants so long as it uses only its declared inputs and outputs, and
Bazel takes care of scheduling actions and caching their results as appropriate.
The system isn’t foolproof given that there’s no way to stop an action developer
from doing something like introducing a nondeterministic process as part of
their action. But this doesn’t happen very often in practice, and pushing the
possibilities for abuse all the way down to the action level greatly decreases
opportunities for errors. Rules supporting many common languages and tools are
widely available online, and most projects will never need to define their own
rules. Even for those that do, rule definitions only need to be defined in one
central place in the repository, meaning most engineers will be able to use
those rules without ever having to worry about their implementation.
### Isolating the environment
Actions sound like they might run into the same problems as tasks in other
systems—isn’t it still possible to write actions that both write to the same
file and end up conflicting with one another? Actually, Bazel makes these
conflicts impossible by using *[sandboxing](/docs/sandboxing)*. On supported
systems, every action is isolated from every other action via a filesystem
sandbox. Effectively, each action can see only a restricted view of the
filesystem that includes the inputs it has declared and any outputs it has
produced. This is enforced by systems such as LXC on Linux, the same technology
behind Docker. This means that it’s impossible for actions to conflict with one
another because they are unable to read any files they don’t declare, and any
files that they write but don’t declare will be thrown away when the action
finishes. Bazel also uses sandboxes to restrict actions from communicating via
the network.
### Making external dependencies deterministic
There’s still one problem remaining: build systems often need to download
dependencies (whether tools or libraries) from external sources rather than
directly building them. This can be seen in the example via the
`@com_google_common_guava_guava//jar` dependency, which downloads a `JAR` file
from Maven.
Depending on files outside of the current workspace is risky. Those files could
change at any time, potentially requiring the build system to constantly check
whether they’re fresh. If a remote file changes without a corresponding change
in the workspace source code, it can also lead to unreproducible builds—a build
might work one day and fail the next for no obvious reason due to an unnoticed
dependency change. Finally, an external dependency can introduce a huge security
risk when it is owned by a third party: if an attacker is able to infiltrate
that third-party server, they can replace the dependency file with something of
their own design, potentially giving them full control over your build
environment and its output.
The fundamental problem is that we want the build system to be aware of these
files without having to check them into source control. Updating a dependency
should be a conscious choice, but that choice should be made once in a central
place rather than managed by individual engineers or automatically by the
system. This is because even with a “Live at Head” model, we still want builds
to be deterministic, which implies that if you check out a commit from last
week, you should see your dependencies as they were then rather than as they are
now.
Bazel and some other build systems address this problem by requiring a
workspacewide manifest file that lists a *cryptographic hash* for every external
dependency in the workspace. The hash is a concise way to uniquely represent the
file without checking the entire file into source control. Whenever a new
external dependency is referenced from a workspace, that dependency’s hash is
added to the manifest, either manually or automatically. When Bazel runs a
build, it checks the actual hash of its cached dependency against the expected
hash defined in the manifest and redownloads the file only if the hash differs.
If the artifact we download has a different hash than the one declared in the
manifest, the build will fail unless the hash in the manifest is updated. This
can be done automatically, but that change must be approved and checked into
source control before the build will accept the new dependency. This means that
there’s always a record of when a dependency was updated, and an external
dependency can’t change without a corresponding change in the workspace source.
It also means that, when checking out an older version of the source code, the
build is guaranteed to use the same dependencies that it was using at the point
when that version was checked in (or else it will fail if those dependencies are
no longer available).
Of course, it can still be a problem if a remote server becomes unavailable or
starts serving corrupt data—this can cause all of your builds to begin failing
if you don’t have another copy of that dependency available. To avoid this
problem, we recommend that, for any nontrivial project, you mirror all of its
dependencies onto servers or services that you trust and control. Otherwise you
will always be at the mercy of a third party for your build system’s
availability, even if the checked-in hashes guarantee its security.
# Why a Build System?
Source: https://bazel.build/basics/build-systems
This page discusses what build systems are, what they do, why you should use a
build system, and why compilers and build scripts aren't the best choice as your
organization starts to scale. It's intended for developers who don't have much
experience with a build system.
## What is a build system?
Fundamentally, all build systems have a straightforward purpose: they transform
the source code written by engineers into executable binaries that can be read
by machines. Build systems aren't just for human-authored code; they also allow
machines to create builds automatically, whether for testing or for releases to
production. In an organization with thousands of engineers, it's common that
most builds are triggered automatically rather than directly by engineers.
### Can't I just use a compiler?
The need for a build system might not be immediately obvious. Most engineers
don't use a build system while learning to code: most start by invoking tools
like `gcc` or `javac` directly from the command line, or the equivalent in an
integrated development environment (IDE). As long as all the source code is in
the same directory, a command like this works fine:
```posix-terminal theme={null}
javac *.java
```
This instructs the Java compiler to take every Java source file in the current
directory and turn it into a binary class file. In the simplest case, this is
all you need.
However, as soon as code expands, the complications begin. `javac` is smart
enough to look in subdirectories of the current directory to find code to
import. But it has no way of finding code stored in *other parts* of the
filesystem (perhaps a library shared by several projects). It also only knows
how to build Java code. Large systems often involve different pieces written in
a variety of programming languages with webs of dependencies among those pieces,
meaning no compiler for a single language can possibly build the entire system.
Once you're dealing with code from multiple languages or multiple compilation
units, building code is no longer a one-step process. Now you must evaluate what
your code depends on and build those pieces in the proper order, possibly using
a different set of tools for each piece. If any dependencies change, you must
repeat this process to avoid depending on stale binaries. For a codebase of even
moderate size, this process quickly becomes tedious and error-prone.
The compiler also doesn’t know anything about how to handle external
dependencies, such as third-party `JAR` files in Java. Without a build system,
you could manage this by downloading the dependency from the internet, sticking
it in a `lib` folder on the hard drive, and configuring the compiler to read
libraries from that directory. Over time, it's difficult to maintain the
updates, versions, and source of these external dependencies.
### What about shell scripts?
Suppose that your hobby project starts out simple enough that you can build it
using just a compiler, but you begin running into some of the problems described
previously. Maybe you still don’t think you need a build system and can automate
away the tedious parts using some simple shell scripts that take care of
building things in the correct order. This helps out for a while, but pretty
soon you start running into even more problems:
* It becomes tedious. As your system grows more complex, you begin spending
almost as much time working on your build scripts as on real code. Debugging
shell scripts is painful, with more and more hacks being layered on top of
one another.
* It’s slow. To make sure you weren’t accidentally relying on stale libraries,
you have your build script build every dependency in order every time you
run it. You think about adding some logic to detect which parts need to be
rebuilt, but that sounds awfully complex and error prone for a script. Or
you think about specifying which parts need to be rebuilt each time, but
then you’re back to square one.
* Good news: it’s time for a release! Better go figure out all the arguments
you need to pass to the jar command to make your final build. And remember
how to upload it and push it out to the central repository. And build and
push the documentation updates, and send out a notification to users. Hmm,
maybe this calls for another script...
* Disaster! Your hard drive crashes, and now you need to recreate your entire
system. You were smart enough to keep all of your source files in version
control, but what about those libraries you downloaded? Can you find them
all again and make sure they were the same version as when you first
downloaded them? Your scripts probably depended on particular tools being
installed in particular places—can you restore that same environment so that
the scripts work again? What about all those environment variables you set a
long time ago to get the compiler working just right and then forgot about?
* Despite the problems, your project is successful enough that you’re able to
begin hiring more engineers. Now you realize that it doesn’t take a disaster
for the previous problems to arise—you need to go through the same painful
bootstrapping process every time a new developer joins your team. And
despite your best efforts, there are still small differences in each
person’s system. Frequently, what works on one person’s machine doesn’t work
on another’s, and each time it takes a few hours of debugging tool paths or
library versions to figure out where the difference is.
* You decide that you need to automate your build system. In theory, this is
as simple as getting a new computer and setting it up to run your build
script every night using cron. You still need to go through the painful
setup process, but now you don’t have the benefit of a human brain being
able to detect and resolve minor problems. Now, every morning when you get
in, you see that last night’s build failed because yesterday a developer
made a change that worked on their system but didn’t work on the automated
build system. Each time it’s a simple fix, but it happens so often that you
end up spending a lot of time each day discovering and applying these simple
fixes.
* Builds become slower and slower as the project grows. One day, while waiting
for a build to complete, you gaze mournfully at the idle desktop of your
coworker, who is on vacation, and wish there were a way to take advantage of
all that wasted computational power.
You’ve run into a classic problem of scale. For a single developer working on at
most a couple hundred lines of code for at most a week or two (which might have
been the entire experience thus far of a junior developer who just graduated
university), a compiler is all you need. Scripts can maybe take you a little bit
farther. But as soon as you need to coordinate across multiple developers and
their machines, even a perfect build script isn’t enough because it becomes very
difficult to account for the minor differences in those machines. At this point,
this simple approach breaks down and it’s time to invest in a real build system.
# Dependency Management
Source: https://bazel.build/basics/dependencies
In looking through the previous pages, one theme repeats over and over: managing
your own code is fairly straightforward, but managing its dependencies is much
more difficult. There are all sorts of dependencies: sometimes there’s a
dependency on a task (such as “push the documentation before I mark a release as
complete”), and sometimes there’s a dependency on an artifact (such as “I need
to have the latest version of the computer vision library to build my code”).
Sometimes, you have internal dependencies on another part of your codebase, and
sometimes you have external dependencies on code or data owned by another team
(either in your organization or a third party). But in any case, the idea of “I
need that before I can have this” is something that recurs repeatedly in the
design of build systems, and managing dependencies is perhaps the most
fundamental job of a build system.
## Dealing with Modules and Dependencies
Projects that use artifact-based build systems like Bazel are broken into a set
of modules, with modules expressing dependencies on one another via `BUILD`
files. Proper organization of these modules and dependencies can have a huge
effect on both the performance of the build system and how much work it takes to
maintain.
## Using Fine-Grained Modules and the 1:1:1 Rule
The first question that comes up when structuring an artifact-based build is
deciding how much functionality an individual module should encompass. In Bazel,
a *module* is represented by a target specifying a buildable unit like a
`java_library` or a `go_binary`. At one extreme, the entire project could be
contained in a single module by putting one `BUILD` file at the root and
recursively globbing together all of that project’s source files. At the other
extreme, nearly every source file could be made into its own module, effectively
requiring each file to list in a `BUILD` file every other file it depends on.
Most projects fall somewhere between these extremes, and the choice involves a
trade-off between performance and maintainability. Using a single module for the
entire project might mean that you never need to touch the `BUILD` file except
when adding an external dependency, but it means that the build system must
always build the entire project all at once. This means that it won’t be able to
parallelize or distribute parts of the build, nor will it be able to cache parts
that it’s already built. One-module-per-file is the opposite: the build system
has the maximum flexibility in caching and scheduling steps of the build, but
engineers need to expend more effort maintaining lists of dependencies whenever
they change which files reference which.
Though the exact granularity varies by language (and often even within
language), Google tends to favor significantly smaller modules than one might
typically write in a task-based build system. A typical production binary at
Google often depends on tens of thousands of targets, and even a moderate-sized
team can own several hundred targets within its codebase. For languages like
Java that have a strong built-in notion of packaging, each directory usually
contains a single package, target, and `BUILD` file (Pants, another build system
based on Bazel, calls this the 1:1:1 rule). Languages with weaker packaging
conventions frequently define multiple targets per `BUILD` file.
The benefits of smaller build targets really begin to show at scale because they
lead to faster distributed builds and a less frequent need to rebuild targets.
The advantages become even more compelling after testing enters the picture, as
finer-grained targets mean that the build system can be much smarter about
running only a limited subset of tests that could be affected by any given
change. Because Google believes in the systemic benefits of using smaller
targets, we’ve made some strides in mitigating the downside by investing in
tooling to automatically manage `BUILD` files to avoid burdening developers.
Some of these tools, such as `buildifier` and `buildozer`, are available with
Bazel in the [`buildtools` directory](https://github.com/bazelbuild/buildtools).
## Minimizing Module Visibility
Bazel and other build systems allow each target to specify a visibility — a
property that determines which other targets may depend on it. A private target
can only be referenced within its own `BUILD` file. A target may grant broader
visibility to the targets of an explicitly defined list of `BUILD` files, or, in
the case of public visibility, to every target in the workspace.
As with most programming languages, it is usually best to minimize visibility as
much as possible. Generally, teams at Google will make targets public only if
those targets represent widely used libraries available to any team at Google.
Teams that require others to coordinate with them before using their code will
maintain an allowlist of customer targets as their target’s visibility. Each
team’s internal implementation targets will be restricted to only directories
owned by the team, and most `BUILD` files will have only one target that isn’t
private.
## Managing Dependencies
Modules need to be able to refer to one another. The downside of breaking a
codebase into fine-grained modules is that you need to manage the dependencies
among those modules (though tools can help automate this). Expressing these
dependencies usually ends up being the bulk of the content in a `BUILD` file.
### Internal dependencies
In a large project broken into fine-grained modules, most dependencies are
likely to be internal; that is, on another target defined and built in the same
source repository. Internal dependencies differ from external dependencies in
that they are built from source rather than downloaded as a prebuilt artifact
while running the build. This also means that there’s no notion of “version” for
internal dependencies—a target and all of its internal dependencies are always
built at the same commit/revision in the repository. One issue that should be
handled carefully with regard to internal dependencies is how to treat
transitive dependencies (Figure 1). Suppose target A depends on target B, which
depends on a common library target C. Should target A be able to use classes
defined in target C?
[](/images/transitive-dependencies.png)
**Figure 1**. Transitive dependencies
As far as the underlying tools are concerned, there’s no problem with this; both
B and C will be linked into target A when it is built, so any symbols defined in
C are known to A. Bazel allowed this for many years, but as Google grew, we
began to see problems. Suppose that B was refactored such that it no longer
needed to depend on C. If B’s dependency on C was then removed, A and any other
target that used C via a dependency on B would break. Effectively, a target’s
dependencies became part of its public contract and could never be safely
changed. This meant that dependencies accumulated over time and builds at Google
started to slow down.
Google eventually solved this issue by introducing a “strict transitive
dependency mode” in Bazel. In this mode, Bazel detects whether a target tries to
reference a symbol without depending on it directly and, if so, fails with an
error and a shell command that can be used to automatically insert the
dependency. Rolling this change out across Google’s entire codebase and
refactoring every one of our millions of build targets to explicitly list their
dependencies was a multiyear effort, but it was well worth it. Our builds are
now much faster given that targets have fewer unnecessary dependencies, and
engineers are empowered to remove dependencies they don’t need without worrying
about breaking targets that depend on them.
As usual, enforcing strict transitive dependencies involved a trade-off. It made
build files more verbose, as frequently used libraries now need to be listed
explicitly in many places rather than pulled in incidentally, and engineers
needed to spend more effort adding dependencies to `BUILD` files. We’ve since
developed tools that reduce this toil by automatically detecting many missing
dependencies and adding them to a `BUILD` files without any developer
intervention. But even without such tools, we’ve found the trade-off to be well
worth it as the codebase scales: explicitly adding a dependency to `BUILD` file
is a one-time cost, but dealing with implicit transitive dependencies can cause
ongoing problems as long as the build target exists. Bazel [enforces strict transitive dependencies](https://blog.bazel.build/2017/06/28/sjd-unused_deps.html)
on Java code by default.
### External dependencies
If a dependency isn’t internal, it must be external. External dependencies are
those on artifacts that are built and stored outside of the build system. The
dependency is imported directly from an artifact repository (typically accessed
over the internet) and used as-is rather than being built from source. One of
the biggest differences between external and internal dependencies is that
external dependencies have versions, and those versions exist independently of
the project’s source code.
### Automatic versus manual dependency management
Build systems can allow the versions of external dependencies to be managed
either manually or automatically. When managed manually, the buildfile
explicitly lists the version it wants to download from the artifact repository,
often using a [semantic version string](https://semver.org/) such
as `1.1.4`. When managed automatically, the source file specifies a range of
acceptable versions, and the build system always downloads the latest one. For
example, Gradle allows a dependency version to be declared as “1.+” to specify
that any minor or patch version of a dependency is acceptable so long as the
major version is 1.
Automatically managed dependencies can be convenient for small projects, but
they’re usually a recipe for disaster on projects of nontrivial size or that are
being worked on by more than one engineer. The problem with automatically
managed dependencies is that you have no control over when the version is
updated. There’s no way to guarantee that external parties won’t make breaking
updates (even when they claim to use semantic versioning), so a build that
worked one day might be broken the next with no easy way to detect what changed
or to roll it back to a working state. Even if the build doesn’t break, there
can be subtle behavior or performance changes that are impossible to track down.
In contrast, because manually managed dependencies require a change in source
control, they can be easily discovered and rolled back, and it’s possible to
check out an older version of the repository to build with older dependencies.
Bazel requires that versions of all dependencies be specified manually. At even
moderate scales, the overhead of manual version management is well worth it for
the stability it provides.
### The One-Version Rule
Different versions of a library are usually represented by different artifacts,
so in theory there’s no reason that different versions of the same external
dependency couldn’t both be declared in the build system under different names.
That way, each target could choose which version of the dependency it wanted to
use. This causes a lot of problems in practice, so Google enforces a strict
[One-Version Rule](https://opensource.google/docs/thirdparty/oneversion/) for
all third-party dependencies in our codebase.
The biggest problem with allowing multiple versions is the diamond dependency
issue. Suppose that target A depends on target B and on v1 of an external
library. If target B is later refactored to add a dependency on v2 of the same
external library, target A will break because it now depends implicitly on two
different versions of the same library. Effectively, it’s never safe to add a
new dependency from a target to any third-party library with multiple versions,
because any of that target’s users could already be depending on a different
version. Following the One-Version Rule makes this conflict impossible—if a
target adds a dependency on a third-party library, any existing dependencies
will already be on that same version, so they can happily coexist.
### Transitive external dependencies
Dealing with the transitive dependencies of an external dependency can be
particularly difficult. Many artifact repositories such as Maven Central, allow
artifacts to specify dependencies on particular versions of other artifacts in
the repository. Build tools like Maven or Gradle often recursively download each
transitive dependency by default, meaning that adding a single dependency in
your project could potentially cause dozens of artifacts to be downloaded in
total.
This is very convenient: when adding a dependency on a new library, it would be
a big pain to have to track down each of that library’s transitive dependencies
and add them all manually. But there’s also a huge downside: because different
libraries can depend on different versions of the same third-party library, this
strategy necessarily violates the One-Version Rule and leads to the diamond
dependency problem. If your target depends on two external libraries that use
different versions of the same dependency, there’s no telling which one you’ll
get. This also means that updating an external dependency could cause seemingly
unrelated failures throughout the codebase if the new version begins pulling in
conflicting versions of some of its dependencies.
Bazel did not use to automatically download transitive dependencies. It used to
employ a `WORKSPACE` file that required all transitive dependencies to be
listed, which led to a lot of pain when managing external dependencies. Bazel
has since added support for automatic transitive external dependency management
in the form of the `MODULE.bazel` file. See [external dependency overview](/external/overview) for more details.
Yet again, the choice here is one between convenience and scalability. Small
projects might prefer not having to worry about managing transitive dependencies
themselves and might be able to get away with using automatic transitive
dependencies. This strategy becomes less and less appealing as the organization
and codebase grows, and conflicts and unexpected results become more and more
frequent. At larger scales, the cost of manually managing dependencies is much
less than the cost of dealing with issues caused by automatic dependency
management.
### Caching build results using external dependencies
External dependencies are most often provided by third parties that release
stable versions of libraries, perhaps without providing source code. Some
organizations might also choose to make some of their own code available as
artifacts, allowing other pieces of code to depend on them as third-party rather
than internal dependencies. This can theoretically speed up builds if artifacts
are slow to build but quick to download.
However, this also introduces a lot of overhead and complexity: someone needs to
be responsible for building each of those artifacts and uploading them to the
artifact repository, and clients need to ensure that they stay up to date with
the latest version. Debugging also becomes much more difficult because different
parts of the system will have been built from different points in the
repository, and there is no longer a consistent view of the source tree.
A better way to solve the problem of artifacts taking a long time to build is to
use a build system that supports remote caching, as described earlier. Such a
build system saves the resulting artifacts from every build to a location that
is shared across engineers, so if a developer depends on an artifact that was
recently built by someone else, the build system automatically downloads it
instead of building it. This provides all of the performance benefits of
depending directly on artifacts while still ensuring that builds are as
consistent as if they were always built from the same source. This is the
strategy used internally by Google, and Bazel can be configured to use a remote
cache.
### Security and reliability of external dependencies
Depending on artifacts from third-party sources is inherently risky. There’s an
availability risk if the third-party source (such as an artifact repository)
goes down, because your entire build might grind to a halt if it’s unable to
download an external dependency. There’s also a security risk: if the
third-party system is compromised by an attacker, the attacker could replace the
referenced artifact with one of their own design, allowing them to inject
arbitrary code into your build. Both problems can be mitigated by mirroring any
artifacts you depend on onto servers you control and blocking your build system
from accessing third-party artifact repositories like Maven Central. The
trade-off is that these mirrors take effort and resources to maintain, so the
choice of whether to use them often depends on the scale of the project. The
security issue can also be completely prevented with little overhead by
requiring the hash of each third-party artifact to be specified in the source
repository, causing the build to fail if the artifact is tampered with. Another
alternative that completely sidesteps the issue is to vendor your project’s
dependencies. When a project vendors its dependencies, it checks them into
source control alongside the project’s source code, either as source or as
binaries. This effectively means that all of the project’s external dependencies
are converted to internal dependencies. Google uses this approach internally,
checking every third-party library referenced throughout Google into a
`third_party` directory at the root of Google’s source tree. However, this works
at Google only because Google’s source control system is custom built to handle
an extremely large monorepo, so vendoring might not be an option for all
organizations.
# Distributed Builds
Source: https://bazel.build/basics/distributed-builds
When you have a large codebase, chains of dependencies can become very deep.
Even simple binaries can often depend on tens of thousands of build targets. At
this scale, it’s simply impossible to complete a build in a reasonable amount
of time on a single machine: no build system can get around the fundamental
laws of physics imposed on a machine’s hardware. The only way to make this work
is with a build system that supports distributed builds wherein the units of
work being done by the system are spread across an arbitrary and scalable
number of machines. Assuming we’ve broken the system’s work into small enough
units (more on this later), this would allow us to complete any build of any
size as quickly as we’re willing to pay for. This scalability is the holy grail
we’ve been working toward by defining an artifact-based build system.
## Remote caching
The simplest type of distributed build is one that only leverages *remote
caching*, which is shown in Figure 1.
[](/images/distributed-build-remote-cache.png)
**Figure 1**. A distributed build showing remote caching
Every system that performs builds, including both developer workstations and
continuous integration systems, shares a reference to a common remote cache
service. This service might be a fast and local short-term storage system like
Redis or a cloud service like Google Cloud Storage. Whenever a user needs to
build an artifact, whether directly or as a dependency, the system first checks
with the remote cache to see if that artifact already exists there. If so, it
can download the artifact instead of building it. If not, the system builds the
artifact itself and uploads the result back to the cache. This means that
low-level dependencies that don’t change very often can be built once and shared
across users rather than having to be rebuilt by each user. At Google, many
artifacts are served from a cache rather than built from scratch, vastly
reducing the cost of running our build system.
For a remote caching system to work, the build system must guarantee that builds
are completely reproducible. That is, for any build target, it must be possible
to determine the set of inputs to that target such that the same set of inputs
will produce exactly the same output on any machine. This is the only way to
ensure that the results of downloading an artifact are the same as the results
of building it oneself. Note that this requires that each artifact in the cache
be keyed on both its target and a hash of its inputs—that way, different
engineers could make different modifications to the same target at the same
time, and the remote cache would store all of the resulting artifacts and serve
them appropriately without conflict.
Of course, for there to be any benefit from a remote cache, downloading an
artifact needs to be faster than building it. This is not always the case,
especially if the cache server is far from the machine doing the build. Google’s
network and build system is carefully tuned to be able to quickly share build
results.
## Remote execution
Remote caching isn’t a true distributed build. If the cache is lost or if you
make a low-level change that requires everything to be rebuilt, you still need
to perform the entire build locally on your machine. The true goal is to support
remote execution, in which the actual work of doing the build can be spread
across any number of workers. Figure 2 depicts a remote execution system.
[](/images/remote-execution-system.png)
**Figure 2**. A remote execution system
The build tool running on each user’s machine (where users are either human
engineers or automated build systems) sends requests to a central build master.
The build master breaks the requests into their component actions and schedules
the execution of those actions over a scalable pool of workers. Each worker
performs the actions asked of it with the inputs specified by the user and
writes out the resulting artifacts. These artifacts are shared across the other
machines executing actions that require them until the final output can be
produced and sent to the user.
The trickiest part of implementing such a system is managing the communication
between the workers, the master, and the user’s local machine. Workers might
depend on intermediate artifacts produced by other workers, and the final output
needs to be sent back to the user’s local machine. To do this, we can build on
top of the distributed cache described previously by having each worker write
its results to and read its dependencies from the cache. The master blocks
workers from proceeding until everything they depend on has finished, in which
case they’ll be able to read their inputs from the cache. The final product is
also cached, allowing the local machine to download it. Note that we also need a
separate means of exporting the local changes in the user’s source tree so that
workers can apply those changes before building.
For this to work, all of the parts of the artifact-based build systems described
earlier need to come together. Build environments must be completely
self-describing so that we can spin up workers without human intervention. Build
processes themselves must be completely self-contained because each step might
be executed on a different machine. Outputs must be completely deterministic so
that each worker can trust the results it receives from other workers. Such
guarantees are extremely difficult for a task-based system to provide, which
makes it nigh-impossible to build a reliable remote execution system on top of
one.
## Distributed builds at Google
Since 2008, Google has been using a distributed build system that employs both
remote caching and remote execution, which is illustrated in Figure 3.
[](/images/high-level-build-system.png)
**Figure 3**. Google’s distributed build system
Google’s remote cache is called ObjFS. It consists of a backend that stores
build outputs in Bigtables distributed throughout our fleet of production
machines and a frontend FUSE daemon named objfsd that runs on each developer’s
machine. The FUSE daemon allows engineers to browse build outputs as if they
were normal files stored on the workstation, but with the file content
downloaded on-demand only for the few files that are directly requested by the
user. Serving file contents on-demand greatly reduces both network and disk
usage, and the system is able to build twice as fast compared to when we stored
all build output on the developer’s local disk.
Google’s remote execution system is called Forge. A Forge client in Blaze
(Bazel's internal equivalent) called
the Distributor sends requests for each action to a job running in our
datacenters called the Scheduler. The Scheduler maintains a cache of action
results, allowing it to return a response immediately if the action has already
been created by any other user of the system. If not, it places the action into
a queue. A large pool of Executor jobs continually read actions from this queue,
execute them, and store the results directly in the ObjFS Bigtables. These
results are available to the executors for future actions, or to be downloaded
by the end user via objfsd.
The end result is a system that scales to efficiently support all builds
performed at Google. And the scale of Google’s builds is truly massive: Google
runs millions of builds executing millions of test cases and producing petabytes
of build outputs from billions of lines of source code every day. Not only does
such a system let our engineers build complex codebases quickly, it also allows
us to implement a huge number of automated tools and systems that rely on our
build.
# Hermeticity
Source: https://bazel.build/basics/hermeticity
This page covers hermeticity, the benefits of using hermetic builds, and
strategies for identifying non-hermetic behavior in your builds.
## Overview
When given the same input source code and product configuration, a hermetic
build system always returns the same output by isolating the build from changes
to the host system.
In order to isolate the build, hermetic builds are insensitive to libraries and
other software installed on the local or remote host machine. They depend on
specific versions of build tools, such as compilers, and dependencies, such as
libraries. This makes the build process self-contained as it doesn't rely on
services external to the build environment.
The two important aspects of hermeticity are:
* **Isolation**: Hermetic build systems treat tools as source code. They
download copies of tools and manage their storage and use inside managed file
trees. This creates isolation between the host machine and local user,
including installed versions of languages.
* **Source identity**: Hermetic build systems try to ensure the sameness of
inputs. Code repositories, such as Git, identify sets of code mutations with a
unique hash code. Hermetic build systems use this hash to identify changes to
the build's input.
## Benefits
The major benefits of hermetic builds are:
* **Speed**: The output of an action can be cached, and the action need not be
run again unless inputs change.
* **Parallel execution**: For given input and output, the build system can
construct a graph of all actions to calculate efficient and parallel
execution. The build system loads the rules and calculates an action graph
and hash inputs to look up in the cache.
* **Multiple builds**: You can build multiple hermetic builds on the same
machine, each build using different tools and versions.
* **Reproducibility**: Hermetic builds are good for troubleshooting because you
know the exact conditions that produced the build.
## Identifying non-hermeticity
If you are preparing to switch to Bazel, migration is easier if you improve
your existing builds' hermeticity in advance. Some common sources of
non-hermeticity in builds are:
* Arbitrary processing in `.mk` files
* Actions or tooling that create files non-deterministically, usually involving
build IDs or timestamps
* System binaries that differ across hosts (such as `/usr/bin` binaries, absolute
paths, system C++ compilers for native C++ rules autoconfiguration)
* Writing to the source tree during the build. This prevents the same source
tree from being used for another target. The first build writes to the source
tree, fixing the source tree for target A. Then trying to build target B may
fail.
## Troubleshooting non-hermetic builds
Starting with local execution, issues that affect local cache hits reveal
non-hermetic actions.
* Ensure null sequential builds: If you run `make` and get a successful build,
running the build again should not rebuild any targets. If you run each build
step twice or on different systems, compare a hash of the file contents and
get results that differ, the build is not reproducible.
* Run steps to
[debug local cache hits](/remote/cache-remote#troubleshooting-cache-hits)
from a variety of potential client machines to ensure that you catch any
cases of client environment leaking into the actions.
* Execute a build within a docker container that contains nothing but the
checked-out source tree and explicit list of host tools. Build breakages and
error messages will catch implicit system dependencies.
* Discover and fix hermeticity problems using
[remote execution rules](/remote/rules#overview).
* Enable strict [sandboxing](/docs/sandboxing)
at the per-action level, since actions in a build can be stateful and affect
the build or the output.
* [Workspace rules](/remote/workspace)
allow developers to add dependencies to external workspaces, but they are
rich enough to allow arbitrary processing to happen in the process. You can
get a log of some potentially non-hermetic actions in Bazel workspace rules by
adding the flag
`--experimental_workspace_rules_log_file=PATH` to
your Bazel command.
Note: Make your build fully hermetic when mixing remote and local execution,
using Bazel’s “dynamic strategy” functionality. Running Bazel inside the remote
Docker container will enable the build to execute the same in both environments.
## Hermeticity with Bazel
For more information about how other projects have had success using hermetic
builds with Bazel, see these BazelCon talks:
* [Building Real-time Systems with Bazel](https://www.youtube.com/watch?v=t_3bckhV_YI) (SpaceX)
* [Bazel Remote Execution and Remote Caching](https://www.youtube.com/watch?v=_bPyEbAyC0s) (Uber and TwoSigma)
* [Faster Builds With Remote Execution and Caching](https://www.youtube.com/watch?v=MyuJRUwT5LI)
* [Fusing Bazel: Faster Incremental Builds](https://www.youtube.com/watch?v=rQd9Zd1ONOw)
* [Remote Execution vs Local Execution](https://www.youtube.com/watch?v=C8wHmIln--g)
* [Improving the Usability of Remote Caching](https://www.youtube.com/watch?v=u5m7V3ZRHLA) (IBM)
* [Building Self Driving Cars with Bazel](https://www.youtube.com/watch?v=Gh4SJuYUoQI\&list=PLxNYxgaZ8Rsf-7g43Z8LyXct9ax6egdSj\&index=4\&t=0s) (BMW)
* [Building Self Driving Cars with Bazel + Q\&A](https://www.youtube.com/watch?v=fjfFe98LTm8\&list=PLxNYxgaZ8Rsf-7g43Z8LyXct9ax6egdSj\&index=29) (GM Cruise)
# Build Basics
Source: https://bazel.build/basics/index
A build system is one of the most important parts of an engineering organization
because each developer interacts with it potentially dozens or hundreds of times
per day. A fully featured build system is necessary to enable developer
productivity as an organization scales. For individual developers, it's
straightforward to just compile your code and so a build system might seem
excessive. But at a larger scale, having a build system helps with managing
shared dependencies, such as relying on another part of the code base, or an
external resource, such as a library. Build systems help to make sure that you
have everything you need to build your code before it starts building. Build
systems also increase velocity when they're set up to help engineers share
resources and results.
This section covers some history and basics of building and build systems,
including design decisions that went into making Bazel. If you're
familiar with artifact-based build systems, such as Bazel, Buck, and Pants, you
can skip this section, but it's a helpful overview to understand why
artifact-based build systems are excellent at enabling scale.
Note: Much of this section's content comes from the *Build Systems and
Build Philosophy* chapter of the
[*Software Engineering at Google* book](https://abseil.io/resources/swe-book/html/ch18.html).
Thank you to the original author, Erik Kuefler, for allowing its reuse and
modification here!
* **[Why a Build System?](/basics/build-systems)**
If you haven't used a build system before, start here. This page covers why
you should use a build system, and why compilers and build scripts aren't
the best choice once your organization starts to scale beyond a few
developers.
* **[Task-Based Build Systems](/basics/task-based-builds)**
This page discusses task-based build systems (such as Make, Maven, and
Gradle) and some of their challenges.
* **[Artifact-Based Build Systems](/basics/artifact-based-builds)**
This page discusses artifact-based build systems in response to the pain
points of task-based build systems.
* **[Distributed Builds](/basics/distributed-builds)**
This page covers distributed builds, or builds that are executed outside of
your local machine. This requires more robust infrastructure to share
resources and build results (and is where the true wizardry happens!)
* **[Dependency Management](/basics/dependencies)**
This page covers some complications of dependencies at a large scale and
strategies to counteract those complications.
# Task-Based Build Systems
Source: https://bazel.build/basics/task-based-builds
This page covers task-based build systems, how they work and some of the
complications that can occur with task-based systems. After shell scripts,
task-based build systems are the next logical evolution of building.
## Understanding task-based build systems
In a task-based build system, the fundamental unit of work is the task. Each
task is a script that can execute any sort of logic, and tasks specify other
tasks as dependencies that must run before them. Most major build systems in use
today, such as Ant, Maven, Gradle, Grunt, and Rake, are task based. Instead of
shell scripts, most modern build systems require engineers to create build files
that describe how to perform the build.
Take this example from the
[Ant manual](https://ant.apache.org/manual/using.html):
```xml theme={null}
simple example build file
```
The buildfile is written in XML and defines some simple metadata about the build
along with a list of tasks (the `` tags in the XML). (Ant uses the word
*target* to represent a *task*, and it uses the word *task* to refer to
*commands*.) Each task executes a list of possible commands defined by Ant,
which here include creating and deleting directories, running `javac`, and
creating a JAR file. This set of commands can be extended by user-provided
plug-ins to cover any sort of logic. Each task can also define the tasks it
depends on via the depends attribute. These dependencies form an acyclic graph,
as seen in Figure 1.
[](/images/task-dependencies.png)
Figure 1. An acyclic graph showing dependencies
Users perform builds by providing tasks to Ant’s command-line tool. For example,
when a user types `ant dist`, Ant takes the following steps:
1. Loads a file named `build.xml` in the current directory and parses it to
create the graph structure shown in Figure 1.
2. Looks for the task named `dist` that was provided on the command line and
discovers that it has a dependency on the task named `compile`.
3. Looks for the task named `compile` and discovers that it has a dependency on
the task named `init`.
4. Looks for the task named `init` and discovers that it has no dependencies.
5. Executes the commands defined in the `init` task.
6. Executes the commands defined in the `compile` task given that all of that
task’s dependencies have been run.
7. Executes the commands defined in the `dist` task given that all of that
task’s dependencies have been run.
In the end, the code executed by Ant when running the `dist` task is equivalent
to the following shell script:
```posix-terminal theme={null}
./createTimestamp.sh
mkdir build/
javac src/* -d build/
mkdir -p dist/lib/
jar cf dist/lib/MyProject-$(date --iso-8601).jar build/*
```
When the syntax is stripped away, the buildfile and the build script actually
aren’t too different. But we’ve already gained a lot by doing this. We can
create new buildfiles in other directories and link them together. We can easily
add new tasks that depend on existing tasks in arbitrary and complex ways. We
need only pass the name of a single task to the `ant` command-line tool, and it
determines everything that needs to be run.
Ant is an old piece of software, originally released in 2000. Other tools like
Maven and Gradle have improved on Ant in the intervening years and essentially
replaced it by adding features like automatic management of external
dependencies and a cleaner syntax without any XML. But the nature of these newer
systems remains the same: they allow engineers to write build scripts in a
principled and modular way as tasks and provide tools for executing those tasks
and managing dependencies among them.
## The dark side of task-based build systems
Because these tools essentially let engineers define any script as a task, they
are extremely powerful, allowing you to do pretty much anything you can imagine
with them. But that power comes with drawbacks, and task-based build systems can
become difficult to work with as their build scripts grow more complex. The
problem with such systems is that they actually end up giving *too much power to
engineers and not enough power to the system*. Because the system has no idea
what the scripts are doing, performance suffers, as it must be very conservative
in how it schedules and executes build steps. And there’s no way for the system
to confirm that each script is doing what it should, so scripts tend to grow in
complexity and end up being another thing that needs debugging.
### Difficulty of parallelizing build steps
Modern development workstations are quite powerful, with multiple cores that are
capable of executing several build steps in parallel. But task-based systems are
often unable to parallelize task execution even when it seems like they should
be able to. Suppose that task A depends on tasks B and C. Because tasks B and C
have no dependency on each other, is it safe to run them at the same time so
that the system can more quickly get to task A? Maybe, if they don’t touch any
of the same resources. But maybe not—perhaps both use the same file to track
their statuses and running them at the same time causes a conflict. There’s no
way in general for the system to know, so either it has to risk these conflicts
(leading to rare but very difficult-to-debug build problems), or it has to
restrict the entire build to running on a single thread in a single process.
This can be a huge waste of a powerful developer machine, and it completely
rules out the possibility of distributing the build across multiple machines.
### Difficulty performing incremental builds
A good build system allows engineers to perform reliable incremental builds such
that a small change doesn’t require the entire codebase to be rebuilt from
scratch. This is especially important if the build system is slow and unable to
parallelize build steps for the aforementioned reasons. But unfortunately,
task-based build systems struggle here, too. Because tasks can do anything,
there’s no way in general to check whether they’ve already been done. Many tasks
simply take a set of source files and run a compiler to create a set of
binaries; thus, they don’t need to be rerun if the underlying source files
haven’t changed. But without additional information, the system can’t say this
for sure—maybe the task downloads a file that could have changed, or maybe it
writes a timestamp that could be different on each run. To guarantee
correctness, the system typically must rerun every task during each build. Some
build systems try to enable incremental builds by letting engineers specify the
conditions under which a task needs to be rerun. Sometimes this is feasible, but
often it’s a much trickier problem than it appears. For example, in languages
like C++ that allow files to be included directly by other files, it’s
impossible to determine the entire set of files that must be watched for changes
without parsing the input sources. Engineers often end up taking shortcuts, and
these shortcuts can lead to rare and frustrating problems where a task result is
reused even when it shouldn’t be. When this happens frequently, engineers get
into the habit of running clean before every build to get a fresh state,
completely defeating the purpose of having an incremental build in the first
place. Figuring out when a task needs to be rerun is surprisingly subtle, and is
a job better handled by machines than humans.
### Difficulty maintaining and debugging scripts
Finally, the build scripts imposed by task-based build systems are often just
difficult to work with. Though they often receive less scrutiny, build scripts
are code just like the system being built, and are easy places for bugs to hide.
Here are some examples of bugs that are very common when working with a
task-based build system:
* Task A depends on task B to produce a particular file as output. The owner
of task B doesn’t realize that other tasks rely on it, so they change it to
produce output in a different location. This can’t be detected until someone
tries to run task A and finds that it fails.
* Task A depends on task B, which depends on task C, which is producing a
particular file as output that’s needed by task A. The owner of task B
decides that it doesn’t need to depend on task C any more, which causes task
A to fail even though task B doesn’t care about task C at all!
* The developer of a new task accidentally makes an assumption about the
machine running the task, such as the location of a tool or the value of
particular environment variables. The task works on their machine, but fails
whenever another developer tries it.
* A task contains a nondeterministic component, such as downloading a file
from the internet or adding a timestamp to a build. Now, people get
potentially different results each time they run the build, meaning that
engineers won’t always be able to reproduce and fix one another’s failures
or failures that occur on an automated build system.
* Tasks with multiple dependencies can create race conditions. If task A
depends on both task B and task C, and task B and C both modify the same
file, task A gets a different result depending on which one of tasks B and C
finishes first.
There’s no general-purpose way to solve these performance, correctness, or
maintainability problems within the task-based framework laid out here. So long
as engineers can write arbitrary code that runs during the build, the system
can’t have enough information to always be able to run builds quickly and
correctly. To solve the problem, we need to take some power out of the hands of
engineers and put it back in the hands of the system and reconceptualize the
role of the system not as running tasks, but as producing artifacts.
This approach led to the creation of artifact-based build systems, like Blaze
and Bazel.
# Sharing Variables
Source: https://bazel.build/build/share-variables
`BUILD` files are intended to be simple and declarative. They will typically
consist of a series of target declarations. As your code base and your `BUILD`
files get larger, you will probably notice some duplication, such as:
```python theme={null}
cc_library(
name = "foo",
copts = ["-DVERSION=5"],
srcs = ["foo.cc"],
)
cc_library(
name = "bar",
copts = ["-DVERSION=5"],
srcs = ["bar.cc"],
deps = [":foo"],
)
```
Code duplication in `BUILD` files is usually fine. This can make the file more
readable: each declaration can be read and understood without any context. This
is important, not only for humans, but also for external tools. For example, a
tool might be able to read and update `BUILD` files to add missing dependencies.
Code refactoring and code reuse might prevent this kind of automated
modification.
If it is useful to share values (for example, if values must be kept in sync),
you can introduce a variable:
```python theme={null}
COPTS = ["-DVERSION=5"]
cc_library(
name = "foo",
copts = COPTS,
srcs = ["foo.cc"],
)
cc_library(
name = "bar",
copts = COPTS,
srcs = ["bar.cc"],
deps = [":foo"],
)
```
Multiple declarations now use the value `COPTS`. By convention, use uppercase
letters to name global constants.
## Sharing variables across multiple BUILD files
If you need to share a value across multiple `BUILD` files, you have to put it
in a `.bzl` file. `.bzl` files contain definitions (variables and functions)
that can be used in `BUILD` files.
In `path/to/variables.bzl`, write:
```python theme={null}
COPTS = ["-DVERSION=5"]
```
Then, you can update your `BUILD` files to access the variable:
```python theme={null}
load("//path/to:variables.bzl", "COPTS")
cc_library(
name = "foo",
copts = COPTS,
srcs = ["foo.cc"],
)
cc_library(
name = "bar",
copts = COPTS,
srcs = ["bar.cc"],
deps = [":foo"],
)
```
# BUILD Style Guide
Source: https://bazel.build/build/style-guide
## Prefer DAMP BUILD files over DRY
The DRY principle — "Don't Repeat Yourself" — encourages uniqueness by
introducing abstractions such as variables and functions to avoid redundancy in
code.
In contrast, the DAMP principle — "Descriptive and Meaningful Phrases" —
encourages readability over uniqueness to make files easier to understand and
maintain.
`BUILD` files aren't code, they are configurations. They aren't tested like
code, but do need to be maintained by people and tools. That makes DAMP better
for them than DRY.
## BUILD.bazel file formatting
`BUILD` file formatting follows the same approach as Go, where a standardized
tool takes care of most formatting issues.
[Buildifier](https://github.com/bazelbuild/buildifier) is a tool that parses and
emits the source code in a standard style. Every `BUILD` file is therefore
formatted in the same automated way, which makes formatting a non-issue during
code reviews. It also makes it easier for tools to understand, edit, and
generate `BUILD` files.
`BUILD` file formatting must match the output of `buildifier`.
### Formatting example
```python theme={null}
# Test code implementing the Foo controller.
package(default_testonly = True)
py_test(
name = "foo_test",
srcs = glob(["*.py"]),
data = [
"//data/production/foo:startfoo",
"//foo",
"//third_party/java/jdk:jdk-k8",
],
flaky = True,
deps = [
":check_bar_lib",
":foo_data_check",
":pick_foo_port",
"//pyglib",
"//testing/pybase",
],
)
```
## File structure
**Recommendation**: Use the following order (every element is optional):
* Package description (a comment)
* All `load()` statements
* The `package()` function.
* Calls to rules and macros
Buildifier makes a distinction between a standalone comment and a comment
attached to an element. If a comment is not attached to a specific element, use
an empty line after it. The distinction is important when doing automated
changes (for example, to keep or remove a comment when deleting a rule).
```python theme={null}
# Standalone comment (such as to make a section in a file)
# Comment for the cc_library below
cc_library(name = "cc")
```
## References to targets in the current package
Files should be referred to by their paths relative to the package directory
(without ever using up-references, such as `..`). Generated files should be
prefixed with "`:`" to indicate that they are not sources. Source files
should not be prefixed with `:`. Rules should be prefixed with `:`. For
example, assuming `x.cc` is a source file:
```python theme={null}
cc_library(
name = "lib",
srcs = ["x.cc"],
hdrs = [":gen_header"],
)
genrule(
name = "gen_header",
srcs = [],
outs = ["x.h"],
cmd = "echo 'int x();' > $@",
)
```
## Target naming
Target names should be descriptive. If a target contains one source file,
the target should generally have a name derived from that source (for example, a
`cc_library` for `chat.cc` could be named `chat`, or a `java_library` for
`DirectMessage.java` could be named `direct_message`).
The eponymous target for a package (the target with the same name as the
containing directory) should provide the functionality described by the
directory name. If there is no such target, do not create an eponymous
target.
Prefer using the short name when referring to an eponymous target (`//x`
instead of `//x:x`). If you are in the same package, prefer the local
reference (`:x` instead of `//x`).
Avoid using "reserved" target names which have special meaning. This includes
`all`, `__pkg__`, and `__subpackages__`, these names have special
semantics and can cause confusion and unexpected behaviors when they are used.
In the absence of a prevailing team convention these are some non-binding
recommendations that are broadly used at Google:
* In general, use ["snake\_case"](https://en.wikipedia.org/wiki/Snake_case)
* For a `java_library` with one `src` this means using a name that is not
the same as the filename without the extension
* For Java `*_binary` and `*_test` rules, use
["Upper CamelCase"](https://en.wikipedia.org/wiki/Camel_case).
This allows for the target name to match one of the `src`s. For
`java_test`, this makes it possible for the `test_class` attribute to be
inferred from the name of the target.
* If there are multiple variants of a particular target then add a suffix to
disambiguate (such as. `:foo_dev`, `:foo_prod` or `:bar_x86`, `:bar_x64`)
* Suffix `_test` targets with `_test`, `_unittest`, `Test`, or `Tests`
* Avoid meaningless suffixes like `_lib` or `_library` (unless necessary to
avoid conflicts between a `_library` target and its corresponding `_binary`)
* For proto related targets:
* `proto_library` targets should have names ending in `_proto`
* Languages specific `*_proto_library` rules should match the underlying
proto but replace `_proto` with a language specific suffix such as:
* **`cc_proto_library`**: `_cc_proto`
* **`java_proto_library`**: `_java_proto`
* **`java_lite_proto_library`**: `_java_proto_lite`
## Visibility
Visibility should be scoped as tightly as possible, while still allowing access
by tests and reverse dependencies. Use `__pkg__` and `__subpackages__` as
appropriate.
Avoid setting package `default_visibility` to `//visibility:public`.
`//visibility:public` should be individually set only for targets in the
project's public API. These could be libraries that are designed to be depended
on by external projects or binaries that could be used by an external project's
build process.
## Dependencies
Dependencies should be restricted to direct dependencies (dependencies
needed by the sources listed in the rule). Do not list transitive dependencies.
Package-local dependencies should be listed first and referred to in a way
compatible with the
[References to targets in the current package](#targets-current-package)
section above (not by their absolute package name).
Prefer to list dependencies directly, as a single list. Putting the "common"
dependencies of several targets into a variable reduces maintainability, makes
it impossible for tools to change the dependencies of a target, and can lead to
unused dependencies.
## Globs
Indicate "no targets" with `[]`. Do not use a glob that matches nothing: it
is more error-prone and less obvious than an empty list.
### Recursive
Do not use recursive globs to match source files (for example,
`glob(["**/*.java"])`).
Recursive globs make `BUILD` files difficult to reason about because they skip
subdirectories containing `BUILD` files.
Recursive globs are generally less efficient than having a `BUILD` file per
directory with a dependency graph defined between them as this enables better
remote caching and parallelism.
It is good practice to author a `BUILD` file in each directory and define a
dependency graph between them.
### Non-recursive
Non-recursive globs are generally acceptable.
## Avoid list comprehensions
Avoid using list comprehensions at the top level of a `BUILD.bazel` file.
Automate repetitive calls by creating each named target with a separate
top-level rule or macro call. Give each a short `name` parameter for clarity.
List comprehension reduces the following:
* Maintainability. It's difficult or impossible for human maintainers and
large scale automated changes to update list comprehensions correctly.
* Discoverability. Since the pattern doesn't have `name` parameters,
it's hard to find the rule by name.
A common application of the list comprehension pattern is to generate tests. For
example:
```build {.bad} theme={null}
[[java_test(
name = "test_%s_%s" % (backend, count),
srcs = [ ... ],
deps = [ ... ],
...
) for backend in [
"fake",
"mock",
]] for count in [
1,
10,
]]
```
We recommend using simpler alternatives. For example, define a macro that
generates one test and invoke it for each top-level `name`:
```build theme={null}
my_java_test(name = "test_fake_1",
...)
my_java_test(name = "test_fake_10",
...)
...
```
## Don't use deps variables
Don't use list variables to encapsulate common dependencies:
```build {.bad} theme={null}
COMMON_DEPS = [
"//d:e",
"//x/y:z",
]
cc_library(name = "a",
srcs = ["a.cc"],
deps = COMMON_DEPS + [ ... ],
)
cc_library(name = "b",
srcs = ["b.cc"],
deps = COMMON_DEPS + [ ... ],
)
```
Similarly, don't use a library target with
[`exports`](/reference/be/java#java_library.exports) to group dependencies.
Instead, list the dependencies separately for each target:
```build {.good} theme={null}
cc_library(name = "a",
srcs = ["a.cc"],
deps = [
"//a:b",
"//x/y:z",
...
],
)
cc_library(name = "b",
srcs = ["b.cc"],
deps = [
"//a:b",
"//x/y:z",
...
],
)
```
Let [Gazelle](https://github.com/bazel-contrib/bazel-gazelle) and other tools
maintain them. There will be repetition, but you won't have to think about how
to manage the dependencies.
## Prefer literal strings
Although Starlark provides string operators for concatenation (`+`) and
formatting (`%`), use them with caution. It is tempting to factor out common
string parts to make expressions more concise or break long lines. However,
* It is harder to read broken-up string values at a glance.
* Automated tools such as
[buildozer][buildozer] and Code Search have trouble finding values and
updating them correctly when the values broken up.
* In `BUILD` files, readability is more important than avoiding repetition
(see [DAMP versus DRY](#prefer-damp-build-files-over-dry)).
* This Style Guide
[warns against splitting label-valued strings](#other-conventions)
and
[explicitly permits long lines](#differences-python-style-guide).
* Buildifier automatically fuses concatenated strings when it detects that
they are labels.
Therefore, prefer explicit, literal strings over concatenated or formatted
strings, especially in label-type attributes such as `name` and `deps`. For
example, this `BUILD` fragment:
```build {.bad} theme={null}
NAME = "foo"
PACKAGE = "//a/b"
proto_library(
name = "%s_proto" % NAME,
deps = [PACKAGE + ":other_proto"],
alt_dep = "//surprisingly/long/chain/of/package/names:" +
"extravagantly_long_target_name",
)
```
would be better rewritten as
```build {.good} theme={null}
proto_library(
name = "foo_proto",
deps = ["//a/b:other_proto"],
alt_dep = "//surprisingly/long/chain/of/package/names:extravagantly_long_target_name",
)
```
[buildozer]: https://github.com/bazelbuild/buildtools/blob/main/buildozer/README.md
## Limit the symbols exported by each `.bzl` file
Minimize the number of symbols (rules, macros, constants, functions) exported by
each public `.bzl` (Starlark) file. We recommend that a file should export
multiple symbols only if they are certain to be used together. Otherwise, split
it into multiple `.bzl` files, each with its own [bzl\_library][bzl_library].
Excessive symbols can cause `.bzl` files to grow into broad "libraries" of
symbols, causing changes to single files to force Bazel to rebuild many targets.
[bzl_library]: https://github.com/bazelbuild/bazel-skylib/blob/main/README.md#bzl_library
## Other conventions
* Use uppercase and underscores to declare constants (such as `GLOBAL_CONSTANT`),
use lowercase and underscores to declare variables (such as `my_variable`).
* Labels should never be split, even if they are longer than 79 characters.
Labels should be string literals whenever possible. *Rationale*: It makes
find and replace easy. It also improves readability.
* The value of the name attribute should be a literal constant string (except
in macros). *Rationale*: External tools use the name attribute to refer a
rule. They need to find rules without having to interpret code.
* When setting boolean-type attributes, use boolean values, not integer values.
For legacy reasons, rules still convert integers to booleans as needed,
but this is discouraged. *Rationale*: `flaky = 1` could be misread as saying
"deflake this target by rerunning it once". `flaky = True` unambiguously says
"this test is flaky".
## Differences with Python style guide
Although compatibility with
[Python style guide](https://www.python.org/dev/peps/pep-0008/)
is a goal, there are a few differences:
* No strict line length limit. Long comments and long strings are often split
to 79 columns, but it is not required. It should not be enforced in code
reviews or presubmit scripts. *Rationale*: Labels can be long and exceed this
limit. It is common for `BUILD` files to be generated or edited by tools,
which does not go well with a line length limit.
* Implicit string concatenation is not supported. Use the `+` operator.
*Rationale*: `BUILD` files contain many string lists. It is easy to forget a
comma, which leads to a complete different result. This has created many bugs
in the past. [See also this discussion.](https://lwn.net/Articles/551438/)
* Use spaces around the `=` sign for keywords arguments in rules. *Rationale*:
Named arguments are much more frequent than in Python and are always on a
separate line. Spaces improve readability. This convention has been around
for a long time, and it is not worth modifying all existing `BUILD` files.
* By default, use double quotation marks for strings. *Rationale*: This is not
specified in the Python style guide, but it recommends consistency. So we
decided to use only double-quoted strings. Many languages use double-quotes
for string literals.
* Use a single blank line between two top-level definitions. *Rationale*: The
structure of a `BUILD` file is not like a typical Python file. It has only
top-level statements. Using a single-blank line makes `BUILD` files shorter.
# Recommended Rules
Source: https://bazel.build/community/recommended-rules
In the documentation, we provide a list of
[recommended rules](/rules).
This is a set of high quality rules, which will provide a good experience to our
users. We make a distinction between the supported rules, and the hundreds of
rules you can find on the Internet.
## Nomination
If a ruleset meets the requirements below, a rule maintainer can nominate it
to be part of the *recommended rules* by filing a
[GitHub issue](https://github.com/bazelbuild/bazel/).
After a review by the [Bazel core team](/contribute/policy), it
will be recommended on the Bazel website.
## Requirements for the rule maintainers
* The ruleset provides an important feature, useful to a large number of Bazel
users (for example, support for a widely popular language).
* The ruleset is well maintained. There must be at least two active maintainers.
* The ruleset is well documented, with examples, and easy to use.
* The ruleset follows the best practices and is performant (see
[the performance guide](/rules/performance)).
* The ruleset has sufficient test coverage.
* The ruleset is tested on
[BuildKite](https://github.com/bazelbuild/continuous-integration/blob/master/buildkite/README.md)
with the latest version of Bazel. Tests should always pass (when used as a
presubmit check).
* The ruleset is also tested with the upcoming incompatible changes. Breakages
should be fixed within two weeks. Migration issues should be reported to the
Bazel team quickly.
## Requirements for Bazel developers
* Recommended rules are frequently tested with Bazel at head (at least once a
day).
* No change in Bazel may break a recommended rule (with the default set of
flags). If it happens, the change should be fixed or rolled back.
## Demotion
If there is a concern that a particular ruleset is no longer meeting the
requirements, a [GitHub issue](https://github.com/bazelbuild/bazel/) should be
filed.
Rule maintainers will be contacted and need to respond in 2 weeks. Based on the
outcome, Bazel core team might make a decision to demote the rule set.
# BUILD files
Source: https://bazel.build/concepts/build-files
The previous sections described packages, targets and labels, and the
build dependency graph abstractly. This section describes the concrete syntax
used to define a package.
By definition, every package contains a `BUILD` file, which is a short
program.
Note: The `BUILD` file can be named either `BUILD` or `BUILD.bazel`. If both
files exist, `BUILD.bazel` takes precedence over `BUILD`.
For simplicity's sake, the documentation refers to these files simply as `BUILD`
files.
`BUILD` files are evaluated using an imperative language,
[Starlark](https://github.com/bazelbuild/starlark/).
They are interpreted as a sequential list of statements.
In general, order does matter: variables must be defined before they are
used, for example. However, most `BUILD` files consist only of declarations of
build rules, and the relative order of these statements is immaterial; all
that matters is *which* rules were declared, and with what values, by the
time package evaluation completes.
When a build rule function, such as `cc_library`, is executed, it creates a
new target in the graph. This target can later be referred using a label.
In simple `BUILD` files, rule declarations can be re-ordered freely without
changing the behavior.
To encourage a clean separation between code and data, `BUILD` files cannot
contain function definitions, `for` statements or `if` statements (but list
comprehensions and `if` expressions are allowed). Functions can be declared in
`.bzl` files instead. Additionally, `*args` and `**kwargs` arguments are not
allowed in `BUILD` files; instead list all the arguments explicitly.
Crucially, programs in Starlark can't perform arbitrary I/O. This invariant
makes the interpretation of `BUILD` files hermetic — dependent only on a known
set of inputs, which is essential for ensuring that builds are reproducible.
For more details, see [Hermeticity](/basics/hermeticity).
Because `BUILD` files need to be updated whenever the dependencies of the
underlying code change, they are typically maintained by multiple people on a
team. `BUILD` file authors should comment liberally to document the role
of each build target, whether or not it is intended for public use, and to
document the role of the package itself.
## Loading an extension
Bazel extensions are files ending in `.bzl`. Use the `load` statement to import
a symbol from an extension.
```
load("//foo/bar:file.bzl", "some_library")
```
This code loads the file `foo/bar/file.bzl` and adds the `some_library` symbol
to the environment. This can be used to load new rules, functions, or constants
(for example, a string or a list). Multiple symbols can be imported by using
additional arguments to the call to `load`. Arguments must be string literals
(no variable) and `load` statements must appear at top-level — they cannot be
in a function body.
The first argument of `load` is a [label](/concepts/labels) identifying a
`.bzl` file. If it's a relative label, it is resolved with respect to the
package (not directory) containing the current `bzl` file. Relative labels in
`load` statements should use a leading `:`.
`load` also supports aliases, therefore, you can assign different names to the
imported symbols.
```
load("//foo/bar:file.bzl", library_alias = "some_library")
```
You can define multiple aliases within one `load` statement. Moreover, the
argument list can contain both aliases and regular symbol names. The following
example is perfectly legal (please note when to use quotation marks).
```
load(":my_rules.bzl", "some_rule", nice_alias = "some_other_rule")
```
In a `.bzl` file, symbols starting with `_` are not exported and cannot be
loaded from another file.
You can use [load visibility](/concepts/visibility#load-visibility) to restrict
who may load a `.bzl` file.
## Types of build rules
The majority of build rules come in families, grouped together by
language. For example, `cc_binary`, `cc_library`
and `cc_test` are the build rules for C++ binaries,
libraries, and tests, respectively. Other languages use the same
naming scheme, with a different prefix, such as `java_*` for
Java. Some of these functions are documented in the
[Build Encyclopedia](/reference/be/overview), but it is possible
for anyone to create new rules.
* `*_binary` rules build executable programs in a given language. After a
build, the executable will reside in the build tool's binary
output tree at the corresponding name for the rule's label,
so `//my:program` would appear at (for example) `$(BINDIR)/my/program`.
In some languages, such rules also create a runfiles directory
containing all the files mentioned in a `data`
attribute belonging to the rule, or any rule in its transitive
closure of dependencies; this set of files is gathered together in
one place for ease of deployment to production.
* `*_test` rules are a specialization of a `*_binary` rule, used for automated
testing. Tests are simply programs that return zero on success.
Like binaries, tests also have runfiles trees, and the files
beneath it are the only files that a test may legitimately open
at runtime. For example, a program `cc_test(name='x',
data=['//foo:bar'])` may open and read `$TEST_SRCDIR/workspace/foo/bar` during execution.
(Each programming language has its own utility function for
accessing the value of `$TEST_SRCDIR`, but they are all
equivalent to using the environment variable directly.)
Failure to observe the rule will cause the test to fail when it is
executed on a remote testing host.
* `*_library` rules specify separately-compiled modules in the given
programming language. Libraries can depend on other libraries,
and binaries and tests can depend on libraries, with the expected
separate-compilation behavior.
## File encoding
`BUILD` and `.bzl` files should be encoded in UTF-8, of which ASCII is a valid
subset. Arbitrary byte sequences are currently allowed, but may stop being
supported in the future.
# Repositories, workspaces, packages, and targets
Source: https://bazel.build/concepts/build-ref
Bazel builds software from source code organized in directory trees called
repositories. A defined set of repositories comprises the workspace. Source
files in repositories are organized in a nested hierarchy of packages, where
each package is a directory that contains a set of related source files and one
`BUILD` file. The `BUILD` file specifies what software outputs can be built from
the source.
### Repositories
Source files used in a Bazel build are organized in *repositories* (often
shortened to *repos*). A repo is a directory tree with a boundary marker file at
its root; such a boundary marker file could be `MODULE.bazel`, `REPO.bazel`, or
in legacy contexts, `WORKSPACE` or `WORKSPACE.bazel`.
The repo in which the current Bazel command is being run is called the *main
repo*. Other, (external) repos are defined by *repo rules*; see [external dependencies overview](/external/overview) for more information.
## Workspace
A *workspace* is the environment shared by all Bazel commands run from the same
main repo. It encompasses the main repo and the set of all defined external
repos.
Note that historically the concepts of "repository" and "workspace" have been
conflated; the term "workspace" has often been used to refer to the main
repository, and sometimes even used as a synonym of "repository".
## Packages
The primary unit of code organization in a repository is the *package*. A
package is a collection of related files and a specification of how they can be
used to produce output artifacts.
A package is defined as a directory containing a
[`BUILD` file](/concepts/build-files) named either `BUILD` or `BUILD.bazel`. A
package includes all files in its directory, plus all subdirectories beneath it,
except those which themselves contain a `BUILD` file. From this definition, no
file or directory may be a part of two different packages.
For example, in the following directory tree there are two packages, `my/app`,
and the subpackage `my/app/tests`. Note that `my/app/data` is not a package, but
a directory belonging to package `my/app`.
```
src/my/app/BUILD
src/my/app/app.cc
src/my/app/data/input.txt
src/my/app/tests/BUILD
src/my/app/tests/test.cc
```
## Targets
A package is a container of *targets*, which are defined in the package's
`BUILD` file. Most targets are one of two principal kinds, *files* and *rules*.
Files are further divided into two kinds. *Source files* are usually written by
the efforts of people, and checked in to the repository. *Generated files*,
sometimes called derived files or output files, are not checked in, but are
generated from source files.
The second kind of target is declared with a *rule*. Each rule instance
specifies the relationship between a set of input and a set of output files. The
inputs to a rule may be source files, but they also may be the outputs of other
rules.
Whether the input to a rule is a source file or a generated file is in most
cases immaterial; what matters is only the contents of that file. This fact
makes it easy to replace a complex source file with a generated file produced by
a rule, such as happens when the burden of manually maintaining a highly
structured file becomes too tiresome, and someone writes a program to derive it.
No change is required to the consumers of that file. Conversely, a generated
file may easily be replaced by a source file with only local changes.
The inputs to a rule may also include *other rules*. The precise meaning of such
relationships is often quite complex and language- or rule-dependent, but
intuitively it is simple: a C++ library rule A might have another C++ library
rule B for an input. The effect of this dependency is that B's header files are
available to A during compilation, B's symbols are available to A during
linking, and B's runtime data is available to A during execution.
An invariant of all rules is that the files generated by a rule always belong to
the same package as the rule itself; it is not possible to generate files into
another package. It is not uncommon for a rule's inputs to come from another
package, though.
Package groups are sets of packages whose purpose is to limit accessibility of
certain rules. Package groups are defined by the `package_group` function. They
have three properties: the list of packages they contain, their name, and other
package groups they include. The only allowed ways to refer to them are from the
`visibility` attribute of rules or from the `default_visibility` attribute of
the `package` function; they do not generate or consume files. For more
information, refer to the [`package_group` documentation](/reference/be/functions#package_group).
# Dependencies
Source: https://bazel.build/concepts/dependencies
A target `A` *depends upon* a target `B` if `B` is needed by `A` at build or
execution time. The *depends upon* relation induces a
[Directed Acyclic Graph](https://en.wikipedia.org/wiki/Directed_acyclic_graph)
(DAG) over targets, and it is called a *dependency graph*.
A target's *direct* dependencies are those other targets reachable by a path
of length 1 in the dependency graph. A target's *transitive* dependencies are
those targets upon which it depends via a path of any length through the graph.
In fact, in the context of builds, there are two dependency graphs, the graph
of *actual dependencies* and the graph of *declared dependencies*. Most of the
time, the two graphs are so similar that this distinction need not be made, but
it is useful for the discussion below.
## Actual and declared dependencies
A target `X` is *actually dependent* on target `Y` if `Y` must be present,
built, and up-to-date in order for `X` to be built correctly. *Built* could
mean generated, processed, compiled, linked, archived, compressed, executed, or
any of the other kinds of tasks that routinely occur during a build.
A target `X` has a *declared dependency* on target `Y` if there is a dependency
edge from `X` to `Y` in the package of `X`.
For correct builds, the graph of actual dependencies *A* must be a subgraph of
the graph of declared dependencies *D*. That is, every pair of
directly-connected nodes `x --> y` in *A* must also be directly connected in
*D*. It can be said that *D* is an *overapproximation* of *A*.
Important: *D* should not be too much of an overapproximation of *A* because
redundant declared dependencies can make builds slower and binaries larger.
`BUILD` file writers must explicitly declare all of the actual direct
dependencies for every rule to the build system, and no more.
Failure to observe this principle causes undefined behavior: the build may fail,
but worse, the build may depend on some prior operations, or upon transitive
declared dependencies the target happens to have. Bazel checks for missing
dependencies and report errors, but it's not possible for this checking to be
complete in all cases.
You need not (and should not) attempt to list everything indirectly imported,
even if it is *needed* by `A` at execution time.
During a build of target `X`, the build tool inspects the entire transitive
closure of dependencies of `X` to ensure that any changes in those targets are
reflected in the final result, rebuilding intermediates as needed.
The transitive nature of dependencies leads to a common mistake. Sometimes,
code in one file may use code provided by an *indirect* dependency — a
transitive but not direct edge in the declared dependency graph. Indirect
dependencies don't appear in the `BUILD` file. Because the rule doesn't
directly depend on the provider, there is no way to track changes, as shown in
the following example timeline:
1. Declared dependencies match actual dependencies
At first, everything works. The code in package `a` uses code in package `b`.
The code in package `b` uses code in package `c`, and thus `a` transitively
depends on `c`.
The declared dependencies overapproximate the actual dependencies. All is well.
2. Adding an undeclared dependency
A latent hazard is introduced when someone adds code to `a` that creates a
direct *actual* dependency on `c`, but forgets to declare it in the build file
`a/BUILD`.
a / a.in
```
import b;
import c;
b.foo();
c.garply();
```
Declared dependency graph
Actual dependency graph
The declared dependencies no longer overapproximate the actual dependencies.
This may build ok, because the transitive closures of the two graphs are equal,
but masks a problem: `a` has an actual but undeclared dependency on `c`.
3. Divergence between declared and actual dependency graphs
The hazard is revealed when someone refactors `b` so that it no longer depends on
`c`, inadvertently breaking `a` through no
fault of their own.
The declared dependency graph is now an underapproximation of the actual
dependencies, even when transitively closed; the build is likely to fail.
The problem could have been averted by ensuring that the actual dependency from
`a` to `c` introduced in Step 2 was properly declared in the `BUILD` file.
## Types of dependencies
Most build rules have three attributes for specifying different kinds of
generic dependencies: `srcs`, `deps` and `data`. These are explained below. For
more details, see
[Attributes common to all rules](/reference/be/common-definitions).
Many rules also have additional attributes for rule-specific kinds of
dependencies, for example, `compiler` or `resources`. These are detailed in the
[Build Encyclopedia](/reference/be/).
### `srcs` dependencies
Files consumed directly by the rule or rules that output source files.
### `deps` dependencies
Rule pointing to separately-compiled modules providing header files,
symbols, libraries, data, etc.
### `data` dependencies
A build target might need some data files to run correctly. These data files
aren't source code: they don't affect how the target is built. For example, a
unit test might compare a function's output to the contents of a file. When you
build the unit test you don't need the file, but you do need it when you run
the test. The same applies to tools that are launched during execution.
The build system runs tests in an isolated directory where only files listed as
`data` are available. Thus, if a binary/library/test needs some files to run,
specify them (or a build rule containing them) in `data`. For example:
```
# I need a config file from a directory named env:
java_binary(
name = "setenv",
...
data = [":env/default_env.txt"],
)
# I need test data from another directory
sh_test(
name = "regtest",
srcs = ["regtest.sh"],
data = [
"//data:file1.txt",
"//data:file2.txt",
...
],
)
```
These files are available using the relative path `path/to/data/file`. In tests,
you can refer to these files by joining the paths of the test's source
directory and the workspace-relative path, for example,
`${TEST_SRCDIR}/workspace/path/to/data/file`.
## Using labels to reference directories
As you look over our `BUILD` files, you might notice that some `data` labels
refer to directories. These labels end with `/.` or `/` like these examples,
which you should not use:
Not recommended —
data = \["//data/regression:unittest/."]
Not recommended —
data = \["testdata/."]
Not recommended —
data = \["testdata/"]
This seems convenient, particularly for tests because it allows a test to
use all the data files in the directory.
But try not to do this. In order to ensure correct incremental rebuilds (and
re-execution of tests) after a change, the build system must be aware of the
complete set of files that are inputs to the build (or test). When you specify
a directory, the build system performs a rebuild only when the directory itself
changes (due to addition or deletion of files), but won't be able to detect
edits to individual files as those changes don't affect the enclosing directory.
Rather than specifying directories as inputs to the build system, you should
enumerate the set of files contained within them, either explicitly or using the
[`glob()`](/reference/be/functions#glob) function. (Use `**` to force the
`glob()` to be recursive.)
Recommended —
data = glob(\["testdata/\*\*"])
Unfortunately, there are some scenarios where directory labels must be used.
For example, if the `testdata` directory contains files whose names don't
conform to the [label syntax](/concepts/labels#labels-lexical-specification),
then explicit enumeration of files, or use of the
[`glob()`](/reference/be/functions#glob) function produces an invalid labels
error. You must use directory labels in this case, but beware of the
associated risk of incorrect rebuilds described above.
If you must use directory labels, keep in mind that you can't refer to the
parent package with a relative `../` path; instead, use an absolute path like
`//data/regression:unittest/.`.
Note: Directory labels are only valid for data dependencies. If you try to use
a directory as a label in an argument other than `data`, it will fail and you
will get a (probably cryptic) error message.
Any external rule, such as a test, that needs to use multiple files must
explicitly declare its dependence on all of them. You can use `filegroup()` to
group files together in the `BUILD` file:
```
filegroup(
name = 'my_data',
srcs = glob(['my_unittest_data/*'])
)
```
You can then reference the label `my_data` as the data dependency in your test.
# Labels
Source: https://bazel.build/concepts/labels
A **label** is an identifier for a target. A typical label in its full canonical
form looks like:
```none theme={null}
@@myrepo//my/app/main:app_binary
```
The first part of the label is the repository name, `@@myrepo`. The double-`@`
syntax signifies that this is a [*canonical* repo name](/external/overview#canonical-repo-name), which is unique within
the workspace. Labels with canonical repo names unambiguously identify a target
no matter which context they appear in.
Often the canonical repo name is an arcane string that looks like
`@@rules_java++toolchains+local_jdk`. What is much more commonly seen is
labels with an [*apparent* repo name](/external/overview#apparent-repo-name),
which looks like:
```
@myrepo//my/app/main:app_binary
```
The only difference is the repo name being prefixed with one `@` instead of two.
This refers to a repo with the apparent name `myrepo`, which could be different
based on the context this label appears in.
In the typical case that a label refers to the same repository from which
it is used, the repo name part may be omitted. So, inside `@@myrepo` the first
label is usually written as
```
//my/app/main:app_binary
```
The second part of the label is the un-qualified package name
`my/app/main`, the path to the package
relative to the repository root. Together, the repository name and the
un-qualified package name form the fully-qualified package name
`@@myrepo//my/app/main`. When the label refers to the same
package it is used in, the package name (and optionally, the colon)
may be omitted. So, inside `@@myrepo//my/app/main`,
this label may be written either of the following ways:
```
app_binary
:app_binary
```
It is a matter of convention that the colon is omitted for files,
but retained for rules, but it is not otherwise significant.
The part of the label after the colon, `app_binary` is the un-qualified target
name. When it matches the last component of the package path, it, and the
colon, may be omitted. So, these two labels are equivalent:
```
//my/app/lib
//my/app/lib:lib
```
The name of a file target in a subdirectory of the package is the file's path
relative to the package root (the directory containing the `BUILD` file). So,
this file is in the `my/app/main/testdata` subdirectory of the repository:
```
//my/app/main:testdata/input.txt
```
Strings like `//my/app` and `@@some_repo//my/app` have two meanings depending on
the context in which they are used: when Bazel expects a label, they mean
`//my/app:app` and `@@some_repo//my/app:app`, respectively. But, when Bazel
expects a package (e.g. in `package_group` specifications), they reference the
package that contains that label.
A common mistake in `BUILD` files is using `//my/app` to refer to a package, or
to *all* targets in a package--it does not. Remember, it is
equivalent to `//my/app:app`, so it names the `app` target in the `my/app`
package of the current repository.
However, the use of `//my/app` to refer to a package is encouraged in the
specification of a `package_group` or in `.bzl` files, because it clearly
communicates that the package name is absolute and rooted in the top-level
directory of the workspace.
Relative labels cannot be used to refer to targets in other packages; the
repository identifier and package name must always be specified in this case.
For example, if the source tree contains both the package `my/app` and the
package `my/app/testdata` (each of these two directories has its own
`BUILD` file), the latter package contains a file named `testdepot.zip`. Here
are two ways (one wrong, one correct) to refer to this file within
`//my/app:BUILD`:
Wrong — testdata is a different package, so you can't use a relative path
testdata/testdepot.zip
Correct — refer to testdata with its full path
//my/app/testdata:testdepot.zip
Labels starting with `@@//` are references to the main
repository, which will still work even from external repositories.
Therefore `@@//a/b/c` is different from
`//a/b/c` when referenced from an external repository.
The former refers back to the main repository, while the latter
looks for `//a/b/c` in the external repository itself.
This is especially relevant when writing rules in the main
repository that refer to targets in the main repository, and will be
used from external repositories.
For information about the different ways you can refer to targets, see
[target patterns](/run/build#specifying-build-targets).
### Lexical specification of a label
Label syntax discourages use of metacharacters that have special meaning to the
shell. This helps to avoid inadvertent quoting problems, and makes it easier to
construct tools and scripts that manipulate labels, such as the
[Bazel Query Language](/query/language).
The precise details of allowed target names are below.
### Target names — `package-name:target-name`
`target-name` is the name of the target within the package. The name of a rule
is the value of the `name` attribute in the rule's declaration in a `BUILD`
file; the name of a file is its pathname relative to the directory containing
the `BUILD` file.
Target names must be composed entirely of characters drawn from the set `a`–`z`,
`A`–`Z`, `0`–`9`, and the punctuation symbols `!%-@^_"#$&'()*-+,;<=>?[]{|}~/.`.
Filenames must be relative pathnames in normal form, which means they must
neither start nor end with a slash (for example, `/foo` and `foo/` are
forbidden) nor contain multiple consecutive slashes as path separators
(for example, `foo//bar`). Similarly, up-level references (`..`) and
current-directory references (`./`) are forbidden.
Wrong — Do not use .. to refer to files in other packages
Correct — Use
//package-name:filename
While it is common to use `/` in the name of a file target, avoid the use of
`/` in the names of rules. Especially when the shorthand form of a label is
used, it may confuse the reader. The label `//foo/bar/wiz` is always a shorthand
for `//foo/bar/wiz:wiz`, even if there is no such package `foo/bar/wiz`; it
never refers to `//foo:bar/wiz`, even if that target exists.
However, there are some situations where use of a slash is convenient, or
sometimes even necessary. For example, the name of certain rules must match
their principal source file, which may reside in a subdirectory of the package.
### Package names — `//package-name:target-name`
The name of a package is the name of the directory containing its `BUILD` file,
relative to the top-level directory of the containing repository.
For example: `my/app`.
On a technical level, Bazel enforces the following:
* Allowed characters in package names are the lowercase letters `a` through `z`,
the uppercase letters `A` through `Z`, the digits `0` through `9`, the
characters ``! \"#$%&'()*+,-.;<=>?@[]^_`{|}`` (yes, there's a space character
in there!), and of course forward slash `/` (since it's the directory
separator).
* Package names may not start or end with a forward slash character `/`.
* Package names may not contain the substring `//`. This wouldn't make
sense---what would the corresponding directory path be?
* Package names may not contain the substring `/./` or `/../` or `/.../` etc.
This enforcement is done to avoid confusion when translating between a logical
package name and a physical directory name, given the semantic meaning of the
dot character in path strings.
On a practical level:
* For a language with a directory structure that is significant to its module
system (for example, Java), it's important to choose directory names that are
valid identifiers in the language. For example, don't start with a leading
digit and avoid special characters, especially underscores and hyphens.
* Although Bazel supports targets in the workspace's root package (for example,
`//:foo`), it's best to leave that package empty so all meaningful packages
have descriptive names.
## Rules
A rule specifies the relationship between inputs and outputs, and the
steps to build the outputs. Rules can be of one of many different
kinds (sometimes called the *rule class*), which produce compiled
executables and libraries, test executables and other supported
outputs as described in the [Build Encyclopedia](/reference/be/overview).
`BUILD` files declare *targets* by invoking *rules*.
In the example below, we see the declaration of the target `my_app`
using the `cc_binary` rule.
```python theme={null}
cc_binary(
name = "my_app",
srcs = ["my_app.cc"],
deps = [
"//absl/base",
"//absl/strings",
],
)
```
Every rule invocation has a `name` attribute (which must be a valid
[target name](#target-names)), that declares a target within the package
of the `BUILD` file.
Every rule has a set of *attributes*; the applicable attributes for a given
rule, and the significance and semantics of each attribute are a function of
the rule's kind; see the [Build Encyclopedia](/reference/be/overview) for a
list of rules and their corresponding attributes. Each attribute has a name and
a type. Some of the common types an attribute can have are integer, label, list
of labels, string, list of strings, output label, list of output labels. Not
all attributes need to be specified in every rule. Attributes thus form a
dictionary from keys (names) to optional, typed values.
The `srcs` attribute present in many rules has type "list of labels"; its
value, if present, is a list of labels, each being the name of a target that is
an input to this rule.
In some cases, the name of the rule kind is somewhat arbitrary, and more
interesting are the names of the files generated by the rule, and this is true
of genrules. For more information, see
[General Rules: genrule](/reference/be/general#genrule).
In other cases, the name is significant: for `*_binary` and `*_test` rules,
for example, the rule name determines the name of the executable produced by
the build.
This directed acyclic graph over targets is called the *target graph* or
*build dependency graph*, and is the domain over which the
[Bazel Query tool](/query/guide) operates.
# Platforms
Source: https://bazel.build/concepts/platforms
## Intro
Bazel can build and test code on a variety of hardware, operating systems, and
system configurations. This can involve different versions of build tools like
linkers and compilers. To help manage this complexity, Bazel has the concepts
of *constraints* and *platforms*.
A *constraint* is a distinguishing property of a build or production machine.
Common constraints are CPU architecture, presence or absence of a GPU, or
version of a locally installed compiler. But constraints can be *anything* that
meaningfully distinguishes machines when orchestrating build work.
A *platform* is a collection of constraints that specifies a complete machine.
Bazel uses this concept to let developers choose which machines they want to
build for, which machines should run compile and test actions, and which
[toolchains](/extending/toolchains) build actions should compile with.
Developers can also use constraints to [select](/docs/configurable-attributes)
custom properties or dependencies on their build rules. For example: "*use
`src_arm.cc` when the build targets an Arm machine*".
## Platform types
Bazel recognizes three roles a platform may play:
* **Host** - The platform on which Bazel itself runs.
* **Execution** - A platform which runs compile actions to produce build outputs.
* **Target** - A platform the code being built should run on.
Note: Builds only have one host platform, but often have multiple execution and
target platforms. For example, both remote Linux CI machines and developer Macs
may run build actions. And mobile apps have code for multiple phone types and
hardware extensions.
Builds generally have three kinds of relationships to platforms:
* **Single-platform builds** - Host, execution, and target platforms are the
same. For example, building on a developer machine without remote execution,
then running the built binary on the same machine.
* **Cross-compilation builds** - Host and execution platforms are the same,
but the target platform is different. For example, building an iOS app on a
Macbook Pro without remote execution.
* **Multi-platform builds** - Host, execution, and target platforms are all
different. For example, building an iOS app on a Macbook Pro and using remote
Linux machines to compile C++ actions that don't need Xcode.
## Specifying platforms
The most common way for developers to use platforms is to specify desired
target machines with the `--platforms` flag:
```shell theme={null}
$ bazel build //:my_linux_app --platforms=//myplatforms:linux_x86
```
Organizations generally maintain their own platform definitions because build
machine setups vary between organizations.
When `--platforms` isn't set, it defaults to `@platforms//host`. This is
specially defined to auto-detect the host machine's OS and CPU properties so
builds target the same machine Bazel runs on. Build rules can
[select](/docs/configurable-attributes) on these properties with the
[@platforms/os](https://github.com/bazelbuild/platforms/blob/main/os/BUILD) and
[@platforms/cpu](https://github.com/bazelbuild/platforms/blob/main/cpu/BUILD)
constraints.
## Generally useful constraints and platforms
To keep the ecosystem consistent, Bazel team maintains a repository with
constraint definitions for the most popular CPU architectures and operating
systems. These are all defined in
[https://github.com/bazelbuild/platforms](https://github.com/bazelbuild/platforms).
Bazel ships with the following special platform definition:
`@platforms//host` (aliased as `@bazel_tools//tools:host_platform`). This
auto-detects the OS and CPU properties of the machine Bazel runs on.
## Defining constraints
Constraints are modeled with the [`constraint_setting`][constraint_setting] and
[`constraint_value`][constraint_value] build rules.
[constraint_setting]: /reference/be/platforms-and-toolchains#constraint_setting
[constraint_value]: /reference/be/platforms-and-toolchains#constraint_value
`constraint_setting` declares a type of property. For example:
```python theme={null}
constraint_setting(name = "cpu")
```
`constraint_value` declares a possible value for that property:
```python theme={null}
constraint_value(
name = "x86",
constraint_setting = ":cpu"
)
```
These can be referenced as labels when defining platforms or customizing build rules
on them. If the above examples are defined in `cpus/BUILD`, you can reference
the `x86` constraint as `//cpus:x86`.
If visibility allows, you can extend an existing `constraint_setting` by
defining your own value for it.
## Defining platforms
The [`platform`](/reference/be/platforms-and-toolchains#platform) build rule
defines a platform as a collection of `constraint_value`s:
```python theme={null}
platform(
name = "linux_x86",
constraint_values = [
"@platforms//os:linux",
"@platforms//cpu:x86",
],
)
```
This models a machine that must have both the `@platforms//os:linux` and `@platforms//cpu:x86`
constraints.
Platforms may only have one `constraint_value` for a given `constraint_setting`.
This means, for example, a platform can't have two CPUs unless you create another
`constraint_setting` type to model the second value.
## Skipping incompatible targets
When building for a specific target platform it is often desirable to skip
targets that will never work on that platform. For example, your Windows device
driver is likely going to generate lots of compiler errors when building on a
Linux machine with `//...`. Use the
[`target_compatible_with`](/reference/be/common-definitions#common.target_compatible_with)
attribute to tell Bazel what target platform constraints your code has.
The simplest use of this attribute restricts a target to a single platform.
The target won't be built for any platform that doesn't satisfy all of the
constraints. The following example restricts `win_driver_lib.cc` to 64-bit
Windows.
```python theme={null}
cc_library(
name = "win_driver_lib",
srcs = ["win_driver_lib.cc"],
target_compatible_with = [
"@platforms//cpu:x86_64",
"@platforms//os:windows",
],
)
```
`:win_driver_lib` is *only* compatible for building with 64-bit Windows and
incompatible with all else. Incompatibility is transitive. Any targets
that transitively depend on an incompatible target are themselves considered
incompatible.
### When are targets skipped?
Targets are skipped when they are considered incompatible and included in the
build as part of a target pattern expansion. For example, the following two
invocations skip any incompatible targets found in a target pattern expansion.
```console theme={null}
$ bazel build --platforms=//:myplatform //...
```
```console theme={null}
$ bazel build --platforms=//:myplatform //:all
```
Incompatible tests in a [`test_suite`](/reference/be/general#test_suite) are
similarly skipped if the `test_suite` is specified on the command line with
[`--expand_test_suites`](/reference/command-line-reference#flag--expand_test_suites).
In other words, `test_suite` targets on the command line behave like `:all` and
`...`. Using `--noexpand_test_suites` prevents expansion and causes
`test_suite` targets with incompatible tests to also be incompatible.
Explicitly specifying an incompatible target on the command line results in an
error message and a failed build.
```console theme={null}
$ bazel build --platforms=//:myplatform //:target_incompatible_with_myplatform
...
ERROR: Target //:target_incompatible_with_myplatform is incompatible and cannot be built, but was explicitly requested.
...
FAILED: Build did NOT complete successfully
```
Incompatible explicit targets are silently skipped if
`--skip_incompatible_explicit_targets` is enabled.
### More expressive constraints
For more flexibility in expressing constraints, use the
`@platforms//:incompatible`
[`constraint_value`](/reference/be/platforms-and-toolchains#constraint_value)
that no platform satisfies.
Use [`select()`](/reference/be/functions#select) in combination with
`@platforms//:incompatible` to express more complicated restrictions. For
example, use it to implement basic OR logic. The following marks a library
compatible with macOS and Linux, but no other platforms.
Note: An empty constraints list is equivalent to "compatible with everything".
```python theme={null}
cc_library(
name = "unixish_lib",
srcs = ["unixish_lib.cc"],
target_compatible_with = select({
"@platforms//os:osx": [],
"@platforms//os:linux": [],
"//conditions:default": ["@platforms//:incompatible"],
}),
)
```
The above can be interpreted as follows:
1. When targeting macOS, the target has no constraints.
2. When targeting Linux, the target has no constraints.
3. Otherwise, the target has the `@platforms//:incompatible` constraint. Because
`@platforms//:incompatible` is not part of any platform, the target is
deemed incompatible.
To make your constraints more readable, use
[skylib](https://github.com/bazelbuild/bazel-skylib)'s
[`selects.with_or()`](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectswith_or).
You can express inverse compatibility in a similar way. The following example
describes a library that is compatible with everything *except* for ARM.
```python theme={null}
cc_library(
name = "non_arm_lib",
srcs = ["non_arm_lib.cc"],
target_compatible_with = select({
"@platforms//cpu:arm": ["@platforms//:incompatible"],
"//conditions:default": [],
}),
)
```
### Detecting incompatible targets using `bazel cquery`
You can use the
[`IncompatiblePlatformProvider`](/rules/lib/providers/IncompatiblePlatformProvider)
in `bazel cquery`'s [Starlark output format](/query/cquery#output-format-definition) to distinguish
incompatible targets from compatible ones.
This can be used to filter out incompatible targets. The example below will
only print the labels for targets that are compatible. Incompatible targets are
not printed.
```console theme={null}
$ cat example.cquery
def format(target):
if "IncompatiblePlatformProvider" not in providers(target):
return target.label
return ""
$ bazel cquery //... --output=starlark --starlark:file=example.cquery
```
### Known Issues
Incompatible targets [ignore visibility restrictions](https://github.com/bazelbuild/bazel/issues/16044).
# Runfiles
Source: https://bazel.build/concepts/runfiles
[Runfiles are a set of files used by a target at runtime (as opposed to build time)](/extending/rules#runfiles).
Do not hardcode runfiles paths. Those contain the [canonical repository name](/external/overview#canonical-repo-name), but [the canonical repository name format is an implementation detail that may change at any time](/external/module#repository_names_and_strict_deps).
Use one of the language-specific runfiles libraries to access them:
* [rules\_cc](https://github.com/bazelbuild/rules_cc/blob/main/cc/runfiles/runfiles.h)
* [rules\_go](https://github.com/bazel-contrib/rules_go/blob/master/go/runfiles/runfiles.go)
* [rules\_python](https://github.com/bazel-contrib/rules_python/blob/main/python/runfiles/runfiles.py)
* [rules\_shell](https://github.com/bazelbuild/rules_shell/blob/main/shell/runfiles/runfiles.bash)
Runfiles are generally referenced by an `rlocationpath` in the form of `$REPO/package/file` where `$REPO` should be the [apparent repository name](/external/overview#apparent-repo-name).
Most runfiles libraries (see below) support functionality to determine the repository of the currently executed target which is useful to refer to other files in the same repository.
Many Bazel rules support [Make Variables](/reference/be/make-variables#predefined_label_variables) to translate from a target to an rlocationpath by using the `$(rlocationpath //package:target)` notation.
Examples:
```python theme={null}
load("@rules_cc//cc:cc_binary.bzl", "cc_binary")
cc_binary(
name = "runfile",
srcs = ["runfile.cc"],
data = ["//examples:runfile.txt"],
deps = ["@rules_cc//cc/runfiles"],
)
```
```cpp theme={null}
#include
#include
#include
#include
#include "rules_cc/cc/runfiles/runfiles.h"
using rules_cc::cc::runfiles::Runfiles;
inline constexpr std::string_view someFile = "examples/runfile.txt";
int main(int argc, char **argv) {
std::string error;
const auto runfiles = Runfiles::Create(argv[0], BAZEL_CURRENT_REPOSITORY, &error);
if (runfiles == nullptr) {
std::cerr << "Failed to create Runfiles object" << error << "\n";
return 1;
}
std::string root = BAZEL_CURRENT_REPOSITORY;
if (root == "") {
root = "_main";
}
const std::string realPathToSomeFile = runfiles->Rlocation(std::filesystem::path(root) / someFile);
std::cout << "The content of the runfile is:\n";
std::ifstream fin(realPathToSomeFile);
std::string line;
while (std::getline(fin, line)) {
std::cout << line << "\n";
}
return 0;
}
```
```python theme={null}
load("@rules_go//go:def.bzl", "go_binary")
go_binary(
name = "runfile",
srcs = ["runfile.go"],
data = ["//examples:runfile.txt"],
deps = ["@rules_go//go/runfiles:go_default_library"],
)
```
```go theme={null}
package main
import (
"fmt"
"log"
"os"
"path/filepath"
"github.com/bazelbuild/rules_go/go/runfiles"
)
const (
someFile = "examples/runfile.txt"
)
func main() {
r, err := runfiles.New()
if err != nil {
log.Fatalf("Failed to create Runfiles object: %v", err)
}
root := runfiles.CallerRepository()
if root == "" {
root = "_main"
}
path, err := r.Rlocation(filepath.Join(root, someFile))
if err != nil {
log.Fatalf("Failed to find rlocation: %v", err)
}
fmt.Println("The content of my runfile is:")
data, err := os.ReadFile(path)
if err != nil {
log.Fatalf("Failed to read file: %v", err)
}
fmt.Print(string(data))
}
```
```python theme={null}
load("@rules_python//python:defs.bzl", "py_binary")
py_binary(
name = "runfile",
srcs = ["runfile.py"],
data = ["//examples:runfile.txt"],
deps = ["@rules_python//python/runfiles"],
)
```
```python theme={null}
import pathlib
from python.runfiles import runfiles
SOME_FILE = pathlib.Path('examples/runfile.txt')
r = runfiles.Create()
root = r.CurrentRepository()
if root == "":
root = "_main"
realPathToSomeFile = r.Rlocation(str(root / SOME_FILE))
print("The content of the runfile is:")
with open(realPathToSomeFile, 'r') as f:
print(f.read())
```
```python theme={null}
load("@rules_shell//shell:sh_binary.bzl", "sh_binary")
sh_binary(
name = "runfile",
srcs = ["runfile.sh"],
data = ["//examples:runfile.txt"],
use_bash_launcher = True,
)
```
```bash theme={null}
#!/bin/bash
SOME_FILE='examples/runfile.txt'
root="$(runfiles_current_repository)"
if [ -z "$root" ]; then
root="_main"
fi
real_path_to_some_file="$(rlocation "${root}/${SOME_FILE}")"
echo "The content of the runfile is:"
cat "${real_path_to_some_file}"
```
# Visibility
Source: https://bazel.build/concepts/visibility
This page covers Bazel's three visibility systems:
[target visibility](#target-visibility),[transitive visibility](#transitive-visibility)
and [load visibility](#load-visibility).
These types of visibility help other developers distinguish between your
library's public API and its implementation details, and help enforce structure
as your workspace grows. You can also use visibility when deprecating a public
API to allow current users while denying new ones.
## Target visibility
**Target visibility** controls who may depend on your target — that is, who may
use your target's label inside an attribute such as `deps`. A target will fail
to build during the [analysis](/reference/glossary#analysis-phase) phase if it
violates the visibility of one of its dependencies.
Generally, a target `A` is visible to a target `B` if they are in the same
location, or if `A` grants visibility to `B`'s location. In the absence of
[symbolic macros](/extending/macros), the term "location" can be simplified
to just "package"; see [below](#symbolic-macros) for more on symbolic macros.
Visibility is specified by listing allowed packages. Allowing a package does not
necessarily mean that its subpackages are also allowed. For more details on
packages and subpackages, see [Concepts and terminology](/concepts/build-ref).
For prototyping, you can disable target visibility enforcement by setting the
flag `--check_visibility=false`. This shouldn't be done for production usage in
submitted code.
The primary way to control visibility is with a rule's
[`visibility`](/reference/be/common-definitions#common.visibility) attribute.
The following subsections describe the attribute's format, how to apply it to
various kinds of targets, and the interaction between the visibility system and
symbolic macros.
### Visibility specifications
All rule targets have a `visibility` attribute that takes a list of labels. Each
label has one of the following forms. With the exception of the last form, these
are just syntactic placeholders that don't correspond to any actual target.
* `"//visibility:public"`: Grants access to all packages.
* `"//visibility:private"`: Does not grant any additional access; only targets
in this location's package can use this target.
* `"//foo/bar:__pkg__"`: Grants access to `//foo/bar` (but not its
subpackages).
* `"//foo/bar:__subpackages__"`: Grants access to `//foo/bar` and all of its
direct and indirect subpackages.
* `"//some_pkg:my_package_group"`: Grants access to all of the packages that
are part of the given [`package_group`](/reference/be/functions#package_group).
* Package groups use a
[different syntax](/reference/be/functions#package_group.packages) for
specifying packages. Within a package group, the forms
`"//foo/bar:__pkg__"` and `"//foo/bar:__subpackages__"` are respectively
replaced by `"//foo/bar"` and `"//foo/bar/..."`. Likewise,
`"//visibility:public"` and `"//visibility:private"` are just `"public"`
and `"private"`.
For example, if `//some/package:mytarget` has its `visibility` set to
`[":__subpackages__", "//tests:__pkg__"]`, then it could be used by any target
that is part of the `//some/package/...` source tree, as well as targets
declared in `//tests/BUILD`, but not by targets defined in
`//tests/integration/BUILD`.
**Best practice:** To make several targets visible to the same set
of packages, use a `package_group` instead of repeating the list in each
target's `visibility` attribute. This increases readability and prevents the
lists from getting out of sync.
**Best practice:** When granting visibility to another team's project, prefer
`__subpackages__` over `__pkg__` to avoid needless visibility churn as that
project evolves and adds new subpackages.
Note: The `visibility` attribute may not specify non-`package_group` targets.
Doing so triggers a "Label does not refer to a package group" or "Cycle in
dependency graph" error.
### Rule target visibility
A rule target's visibility is determined by taking its `visibility` attribute
\-- or a suitable default if not given -- and appending the location where the
target was declared. For targets not declared in a symbolic macro, if the
package specifies a [`default_visibility`](/reference/be/functions#package.default_visibility),
this default is used; for all other packages and for targets declared in a
symbolic macro, the default is just `["//visibility:private"]`.
```starlark theme={null}
# //mypkg/BUILD
package(default_visibility = ["//friend:__pkg__"])
cc_library(
name = "t1",
...
# No visibility explicitly specified.
# Effective visibility is ["//friend:__pkg__", "//mypkg:__pkg__"].
# If no default_visibility were given in package(...), the visibility would
# instead default to ["//visibility:private"], and the effective visibility
# would be ["//mypkg:__pkg__"].
)
cc_library(
name = "t2",
...
visibility = [":clients"],
# Effective visibility is ["//mypkg:clients, "//mypkg:__pkg__"], which will
# expand to ["//another_friend:__subpackages__", "//mypkg:__pkg__"].
)
cc_library(
name = "t3",
...
visibility = ["//visibility:private"],
# Effective visibility is ["//mypkg:__pkg__"]
)
package_group(
name = "clients",
packages = ["//another_friend/..."],
)
```
**Best practice:** Avoid setting `default_visibility` to public. It may be
convenient for prototyping or in small codebases, but the risk of inadvertently
creating public targets increases as the codebase grows. It's better to be
explicit about which targets are part of a package's public interface.
### Generated file target visibility
A generated file target has the same visibility as the rule target that
generates it.
```starlark theme={null}
# //mypkg/BUILD
java_binary(
name = "foo",
...
visibility = ["//friend:__pkg__"],
)
```
```starlark theme={null}
# //friend/BUILD
some_rule(
name = "bar",
deps = [
# Allowed directly by visibility of foo.
"//mypkg:foo",
# Also allowed. The java_binary's "_deploy.jar" implicit output file
# target the same visibility as the rule target itself.
"//mypkg:foo_deploy.jar",
]
...
)
```
### Source file target visibility
Source file targets can either be explicitly declared using
[`exports_files`](/reference/be/functions#exports_files), or implicitly created
by referring to their filename in a label attribute of a rule (outside of a
symbolic macro). As with rule targets, the location of the call to
`exports_files`, or the BUILD file that referred to the input file, is always
automatically appended to the file's visibility.
Files declared by `exports_files` can have their visibility set by the
`visibility` parameter to that function. If this parameter is not given, the visibility is public.
Note: `exports_files` may not be used to override the visibility of a generated
file.
For files that do not appear in a call to `exports_files`, the visibility
depends on the value of the flag
[`--incompatible_no_implicit_file_export`](https://github.com/bazelbuild/bazel/issues/10225):
* If the flag is true, the visibility is private.
* Else, the legacy behavior applies: The visibility is the same as the
`BUILD` file's `default_visibility`, or private if a default visibility is
not specified.
Avoid relying on the legacy behavior. Always write an `exports_files`
declaration whenever a source file target needs non-private visibility.
**Best practice:** When possible, prefer to expose a rule target rather than a
source file. For example, instead of calling `exports_files` on a `.java` file,
wrap the file in a non-private `java_library` target. Generally, rule targets
should only directly reference source files that live in the same package.
#### Example
File `//frobber/data/BUILD`:
```starlark theme={null}
exports_files(["readme.txt"])
```
File `//frobber/bin/BUILD`:
```starlark theme={null}
cc_binary(
name = "my-program",
data = ["//frobber/data:readme.txt"],
)
```
### Config setting visibility
Historically, Bazel has not enforced visibility for
[`config_setting`](/reference/be/general#config_setting) targets that are
referenced in the keys of a [`select()`](/reference/be/functions#select). There
are two flags to remove this legacy behavior:
* [`--incompatible_enforce_config_setting_visibility`](https://github.com/bazelbuild/bazel/issues/12932)
enables visibility checking for these targets. To assist with migration, it
also causes any `config_setting` that does not specify a `visibility` to be
considered public (regardless of package-level `default_visibility`).
* [`--incompatible_config_setting_private_default_visibility`](https://github.com/bazelbuild/bazel/issues/12933)
causes `config_setting`s that do not specify a `visibility` to respect the
package's `default_visibility` and to fallback on private visibility, just
like any other rule target. It is a no-op if
`--incompatible_enforce_config_setting_visibility` is not set.
Avoid relying on the legacy behavior. Any `config_setting` that is intended to
be used outside the current package should have an explicit `visibility`, if the
package does not already specify a suitable `default_visibility`.
### Package group target visibility
`package_group` targets do not have a `visibility` attribute. They are always
publicly visible.
### Visibility of implicit dependencies
Some rules have [implicit dependencies](/extending/rules#private_attributes_and_implicit_dependencies) —
dependencies that are not spelled out in a `BUILD` file but are inherent to
every instance of that rule. For example, a `cc_library` rule might create an
implicit dependency from each of its rule targets to an executable target
representing a C++ compiler.
The visibility of such an implicit dependency is checked with respect to the
package containing the `.bzl` file in which the rule (or aspect) is defined. In
our example, the C++ compiler could be private so long as it lives in the same
package as the definition of the `cc_library` rule. As a fallback, if the
implicit dependency is not visible from the definition, it is checked with
respect to the `cc_library` target.
If you want to restrict the usage of a rule to certain packages, use
[load visibility](#load-visibility) instead.
### Visibility and symbolic macros
This section describes how the visibility system interacts with
[symbolic macros](/extending/macros).
#### Locations within symbolic macros
A key detail of the visibility system is how we determine the location of a
declaration. For targets that are not declared in a symbolic macro, the location
is just the package where the target lives -- the package of the `BUILD` file.
But for targets created in a symbolic macro, the location is the package
containing the `.bzl` file where the macro's definition (the
`my_macro = macro(...)` statement) appears. When a target is created inside
multiple nested targets, it is always the innermost symbolic macro's definition
that is used.
The same system is used to determine what location to check against a given
dependency's visibility. If the consuming target was created inside a macro, we
look at the innermost macro's definition rather than the package the consuming
target lives in.
This means that all macros whose code is defined in the same package are
automatically "friends" with one another. Any target directly created by a macro
defined in `//lib:defs.bzl` can be seen from any other macro defined in `//lib`,
regardless of what packages the macros are actually instantiated in. Likewise,
they can see, and can be seen by, targets declared directly in `//lib/BUILD` and
its legacy macros. Conversely, targets that live in the same package cannot
necessarily see one another if at least one of them is created by a symbolic
macro.
Within a symbolic macro's implementation function, the `visibility` parameter
has the effective value of the macro's `visibility` attribute after appending
the location where the macro was called. The standard way for a macro to export
one of its targets to its caller is to forward this value along to the target's
declaration, as in `some_rule(..., visibility = visibility)`. Targets that omit
this attribute won't be visible to the caller of the macro unless the caller
happens to be in the same package as the macro definition. This behavior
composes, in the sense that a chain of nested calls to submacros may each pass
`visibility = visibility`, re-exporting the inner macro's exported targets to
the caller at each level, without exposing any of the macros' implementation
details.
#### Delegating privileges to a submacro
The visibility model has a special feature to allow a macro to delegate its
permissions to a submacro. This is important for factoring and composing macros.
Suppose you have a macro `my_macro` that creates a dependency edge using a rule
`some_library` from another package:
```starlark theme={null}
# //macro/defs.bzl
load("//lib:defs.bzl", "some_library")
def _impl(name, visibility, ...):
...
native.genrule(
name = name + "_dependency"
...
)
some_library(
name = name + "_consumer",
deps = [name + "_dependency"],
...
)
my_macro = macro(implementation = _impl, ...)
```
```starlark theme={null}
# //pkg/BUILD
load("//macro:defs.bzl", "my_macro")
my_macro(name = "foo", ...)
```
The `//pkg:foo_dependency` target has no `visibility` specified, so it is only
visible within `//macro`, which works fine for the consuming target. Now, what
happens if the author of `//lib` refactors `some_library` to instead be
implemented using a macro?
```starlark theme={null}
# //lib:defs.bzl
def _impl(name, visibility, deps, ...):
some_rule(
# Main target, exported.
name = name,
visibility = visibility,
deps = deps,
...)
some_library = macro(implementation = _impl, ...)
```
With this change, `//pkg:foo_consumer`'s location is now `//lib` rather than
`//macro`, so its usage of `//pkg:foo_dependency` violates the dependency's
visibility. The author of `my_macro` can't be expected to pass
`visibility = ["//lib"]` to the declaration of the dependency just to work
around this implementation detail.
For this reason, when a dependency of a target is also an attribute value of the
macro that declared the target, we check the dependency's visibility against the
location of the macro instead of the location of the consuming target.
In this example, to validate whether `//pkg:foo_consumer` can see
`//pkg:foo_dependency`, we see that `//pkg:foo_dependency` was also passed as an
input to the call to `some_library` inside of `my_macro`, and instead check the
dependency's visibility against the location of this call, `//macro`.
This process can repeat recursively, as long as a target or macro declaration is
inside of another symbolic macro taking the dependency's label in one of its
label-typed attributes.
Note: Visibility delegation does not work for labels that were not passed into
the macro, such as labels derived by string manipulation.
#### Finalizers
Targets declared in a rule finalizer (a symbolic macro with `finalizer = True`),
in addition to seeing targets following the usual symbolic macro visibility
rules, can *also* see all targets which are visible to the finalizer target's
package.
In other words, if you migrate a `native.existing_rules()`-based legacy macro to
a finalizer, the targets declared by the finalizer will still be able to see
their old dependencies.
It is possible to define targets that a finalizer can introspect using
`native.existing_rules()`, but which it cannot use as dependencies under the
visibility system. For example, if a macro-defined target is not visible to its
own package or to the finalizer macro's definition, and is not delegated to the
finalizer, the finalizer cannot see such a target. Note, however, that a
`native.existing_rules()`-based legacy macro will also be unable to see such a
target.
## Transitive visibility
**Transitive visibility** is a way of restricting who may depend on a target,
including when the dependency is only indirect. It applies separately from the
ordinary target visibility system, so it is possible for a transitive visibility
error to occur even when every link in the dependency chain is valid. This
allows the author of the target to share it with a trusted set of client targets
while guarding against inadvertently leaking it to the rest of the build.
Transitive visibility is declared at the package level, using the
`transitive_visibility` parameter of the \[`package`]\[package]
function. This declaration applies to all targets in the package. The parameter
takes a single label of a `package_group`, which specifies the packages whose
targets may transitively depend on this package's targets.
```starlark theme={null}
# //third_party/sensitive_dep/BUILD
package(
# This must be explicitly listed
transitive_visibility = [":sensitive_dep_users"]
)
package_group(
name = "sensitive_dep_users",
packages = [
"//third_party/sensitive_dep/...", # has to include itself
"//allowed",
],
)
sh_library(
name = "sensitive_dep"
)
```
```starlark theme={null}
# //not_allowed/BUILD
sh_binary(
name = "bad",
deps = ["//third_party/sensitive_dep:sensitive_dep"]
)
```
Building `//not_allowed:bad`, which depends on
`//third_party/sensitive_dep:sensitive_dep` but is not part of its
`transitive_visibility`, results in the following error:
```none theme={null}
Transitive visibility error: //third_party/sensitive_dep:sensitive_dep is not transitively visible from ///not_allowed:bad. //"//third_party/sensitive_dep:sensitive_dep inherits a transitive_visibility declaration from its package or one of its dependencies that does not allow //not_allowed:bad.
```
Package groups used in `transitive_visibility` may not `include` other package
groups.
Note that if a target has a transitive dependency with a transitive visibility
restriction, that target itself inherits the restriction and passes it along to
targets that depend on it. If a target has multiple transitive dependencies
with transitive visibility restrictions, it must meet all of the restrictions.
Transitive visibility also applies to targets that are declared in symbolic
macros. However, unlike ordinary target visibility, it only considers the
package these targets live in, not the package that defined the symbolic macro.
## Load visibility
**Load visibility** controls whether a `.bzl` file may be loaded from other
`BUILD` or `.bzl` files outside the current package.
In the same way that target visibility protects source code that is encapsulated
by targets, load visibility protects build logic that is encapsulated by `.bzl`
files. For instance, a `BUILD` file author might wish to factor some repetitive
target declarations into a macro in a `.bzl` file. Without the protection of
load visibility, they might find their macro reused by other collaborators in
the same workspace, so that modifying the macro breaks other teams' builds.
Note that a `.bzl` file may or may not have a corresponding source file target.
If it does, there is no guarantee that the load visibility and the target
visibility coincide. That is, the same `BUILD` file might be able to load the
`.bzl` file but not list it in the `srcs` of a [`filegroup`](/reference/be/general#filegroup),
or vice versa. This can sometimes cause problems for rules that wish to consume
`.bzl` files as source code, such as for documentation generation or testing.
For prototyping, you may disable load visibility enforcement by setting
`--check_bzl_visibility=false`. As with `--check_visibility=false`, this should
not be done for submitted code.
Load visibility is available as of Bazel 6.0.
### Declaring load visibility
To set the load visibility of a `.bzl` file, call the
[`visibility()`](/rules/lib/globals/bzl#visibility) function from within the file.
The argument to `visibility()` is a list of package specifications, just like
the [`packages`](/reference/be/functions#package_group.packages) attribute of
`package_group`. However, `visibility()` does not accept negative package
specifications.
The call to `visibility()` must only occur once per file, at the top level (not
inside a function), and ideally immediately following the `load()` statements.
Unlike target visibility, the default load visibility is always public. Files
that do not call `visibility()` are always loadable from anywhere in the
workspace. It is a good idea to add `visibility("private")` to the top of any
new `.bzl` file that is not specifically intended for use outside the package.
### Example
```starlark theme={null}
# //mylib/internal_defs.bzl
# Available to subpackages and to mylib's tests.
visibility(["//mylib/...", "//tests/mylib/..."])
def helper(...):
...
```
```starlark theme={null}
# //mylib/rules.bzl
load(":internal_defs.bzl", "helper")
# Set visibility explicitly, even though public is the default.
# Note the [] can be omitted when there's only one entry.
visibility("public")
myrule = rule(
...
)
```
```starlark theme={null}
# //someclient/BUILD
load("//mylib:rules.bzl", "myrule") # ok
load("//mylib:internal_defs.bzl", "helper") # error
...
```
### Load visibility practices
This section describes tips for managing load visibility declarations.
#### Factoring visibilities
When multiple `.bzl` files should have the same visibility, it can be helpful to
factor their package specifications into a common list. For example:
```starlark theme={null}
# //mylib/internal_defs.bzl
visibility("private")
clients = [
"//foo",
"//bar/baz/...",
...
]
```
```starlark theme={null}
# //mylib/feature_A.bzl
load(":internal_defs.bzl", "clients")
visibility(clients)
...
```
```starlark theme={null}
# //mylib/feature_B.bzl
load(":internal_defs.bzl", "clients")
visibility(clients)
...
```
This helps prevent accidental skew between the various `.bzl` files'
visibilities. It also is more readable when the `clients` list is large.
#### Composing visibilities
Sometimes a `.bzl` file might need to be visible to an allowlist that is
composed of multiple smaller allowlists. This is analogous to how a
`package_group` can incorporate other `package_group`s via its
[`includes`](/reference/be/functions#package_group.includes) attribute.
Suppose you are deprecating a widely used macro. You want it to be visible only
to existing users and to the packages owned by your own team. You might write:
```starlark theme={null}
# //mylib/macros.bzl
load(":internal_defs.bzl", "our_packages")
load("//some_big_client:defs.bzl", "their_remaining_uses")
# List concatenation. Duplicates are fine.
visibility(our_packages + their_remaining_uses)
```
#### Deduplicating with package groups
Unlike target visibility, you cannot define a load visibility in terms of a
`package_group`. If you want to reuse the same allowlist for both target
visibility and load visibility, it's best to move the list of package
specifications into a .bzl file, where both kinds of declarations may refer to
it. Building off the example in [Factoring visibilities](#factoring-visibilities)
above, you might write:
```starlark theme={null}
# //mylib/BUILD
load(":internal_defs", "clients")
package_group(
name = "my_pkg_grp",
packages = clients,
)
```
This only works if the list does not contain any negative package
specifications.
#### Protecting individual symbols
Any Starlark symbol whose name begins with an underscore cannot be loaded from
another file. This makes it easy to create private symbols, but does not allow
you to share these symbols with a limited set of trusted files. On the other
hand, load visibility gives you control over what other packages may see your
`.bzl file`, but does not allow you to prevent any non-underscored symbol from
being loaded.
Luckily, you can combine these two features to get fine-grained control.
```starlark theme={null}
# //mylib/internal_defs.bzl
# Can't be public, because internal_helper shouldn't be exposed to the world.
visibility("private")
# Can't be underscore-prefixed, because this is
# needed by other .bzl files in mylib.
def internal_helper(...):
...
def public_util(...):
...
```
```starlark theme={null}
# //mylib/defs.bzl
load(":internal_defs", "internal_helper", _public_util="public_util")
visibility("public")
# internal_helper, as a loaded symbol, is available for use in this file but
# can't be imported by clients who load this file.
...
# Re-export public_util from this file by assigning it to a global variable.
# We needed to import it under a different name ("_public_util") in order for
# this assignment to be legal.
public_util = _public_util
```
#### bzl-visibility Buildifier lint
There is a [Buildifier lint](https://github.com/bazelbuild/buildtools/blob/master/WARNINGS.md#bzl-visibility)
that provides a warning if users load a file from a directory named `internal`
or `private`, when the user's file is not itself underneath the parent of that
directory. This lint predates the load visibility feature and is unnecessary in
workspaces where `.bzl` files declare visibilities.
# Configurable Build Attributes
Source: https://bazel.build/configure/attributes
***Configurable attributes***, commonly known as [`select()`](/reference/be/functions#select), is a Bazel feature that lets users toggle the values
of build rule attributes at the command line.
This can be used, for example, for a multiplatform library that automatically
chooses the appropriate implementation for the architecture, or for a
feature-configurable binary that can be customized at build time.
## Example
```python theme={null}
# myapp/BUILD
cc_binary(
name = "mybinary",
srcs = ["main.cc"],
deps = select({
":arm_build": [":arm_lib"],
":x86_debug_build": [":x86_dev_lib"],
"//conditions:default": [":generic_lib"],
}),
)
config_setting(
name = "arm_build",
values = {"cpu": "arm"},
)
config_setting(
name = "x86_debug_build",
values = {
"cpu": "x86",
"compilation_mode": "dbg",
},
)
```
This declares a `cc_binary` that "chooses" its deps based on the flags at the
command line. Specifically, `deps` becomes:
Command
deps =
bazel build //myapp:mybinary --cpu=arm
\[":arm\_lib"]
bazel build //myapp:mybinary -c dbg --cpu=x86
\[":x86\_dev\_lib"]
bazel build //myapp:mybinary --cpu=ppc
\[":generic\_lib"]
bazel build //myapp:mybinary -c dbg --cpu=ppc
\[":generic\_lib"]
`select()` serves as a placeholder for a value that will be chosen based on
*configuration conditions*, which are labels referencing [`config_setting`](/reference/be/general#config_setting)
targets. By using `select()` in a configurable attribute, the attribute
effectively adopts different values when different conditions hold.
Matches must be unambiguous: if multiple conditions match then either
* They all resolve to the same value. For example, when running on linux x86, this is unambiguous
`{"@platforms//os:linux": "Hello", "@platforms//cpu:x86_64": "Hello"}` because both branches resolve to "hello".
* One's `values` is a strict superset of all others'. For example, `values = {"cpu": "x86", "compilation_mode": "dbg"}`
is an unambiguous specialization of `values = {"cpu": "x86"}`.
The built-in condition [`//conditions:default`](#default-condition) automatically matches when
nothing else does.
While this example uses `deps`, `select()` works just as well on `srcs`,
`resources`, `cmd`, and most other attributes. Only a small number of attributes
are *non-configurable*, and these are clearly annotated. For example,
`config_setting`'s own
[`values`](/reference/be/general#config_setting.values) attribute is non-configurable.
## `select()` and dependencies
Certain attributes change the build parameters for all transitive dependencies
under a target. For example, `genrule`'s `tools` changes `--cpu` to the CPU of
the machine running Bazel (which, thanks to cross-compilation, may be different
than the CPU the target is built for). This is known as a
[configuration transition](/reference/glossary#transition).
Given
```python theme={null}
#myapp/BUILD
config_setting(
name = "arm_cpu",
values = {"cpu": "arm"},
)
config_setting(
name = "x86_cpu",
values = {"cpu": "x86"},
)
genrule(
name = "my_genrule",
srcs = select({
":arm_cpu": ["g_arm.src"],
":x86_cpu": ["g_x86.src"],
}),
tools = select({
":arm_cpu": [":tool1"],
":x86_cpu": [":tool2"],
}),
)
cc_binary(
name = "tool1",
srcs = select({
":arm_cpu": ["armtool.cc"],
":x86_cpu": ["x86tool.cc"],
}),
)
```
running
```sh theme={null}
$ bazel build //myapp:my_genrule --cpu=arm
```
on an `x86` developer machine binds the build to `g_arm.src`, `tool1`, and
`x86tool.cc`. Both of the `select`s attached to `my_genrule` use `my_genrule`'s
build parameters, which include `--cpu=arm`. The `tools` attribute changes
`--cpu` to `x86` for `tool1` and its transitive dependencies. The `select` on
`tool1` uses `tool1`'s build parameters, which include `--cpu=x86`.
## Configuration conditions
Each key in a configurable attribute is a label reference to a
[`config_setting`](/reference/be/general#config_setting) or
[`constraint_value`](/reference/be/platforms-and-toolchains#constraint_value).
`config_setting` is just a collection of
expected command line flag settings. By encapsulating these in a target, it's
easy to maintain "standard" conditions users can reference from multiple places.
`constraint_value` provides support for [multi-platform behavior](#platforms).
### Built-in flags
Flags like `--cpu` are built into Bazel: the build tool natively understands
them for all builds in all projects. These are specified with
[`config_setting`](/reference/be/general#config_setting)'s
[`values`](/reference/be/general#config_setting.values) attribute:
```python theme={null}
config_setting(
name = "meaningful_condition_name",
values = {
"flag1": "value1",
"flag2": "value2",
...
},
)
```
`flagN` is a flag name (without `--`, so `"cpu"` instead of `"--cpu"`). `valueN`
is the expected value for that flag. `:meaningful_condition_name` matches if
*every* entry in `values` matches. Order is irrelevant.
`valueN` is parsed as if it was set on the command line. This means:
* `values = { "compilation_mode": "opt" }` matches `bazel build -c opt`
* `values = { "force_pic": "true" }` matches `bazel build --force_pic=1`
* `values = { "force_pic": "0" }` matches `bazel build --noforce_pic`
`config_setting` only supports flags that affect target behavior. For example,
[`--show_progress`](/docs/user-manual#show-progress) isn't allowed because
it only affects how Bazel reports progress to the user. Targets can't use that
flag to construct their results. The exact set of supported flags isn't
documented. In practice, most flags that "make sense" work.
### Custom flags
You can model your own project-specific flags with
[Starlark build settings][BuildSettings]. Unlike built-in flags, these are
defined as build targets, so Bazel references them with target labels.
These are triggered with [`config_setting`](/reference/be/general#config_setting)'s
[`flag_values`](/reference/be/general#config_setting.flag_values)
attribute:
```python theme={null}
config_setting(
name = "meaningful_condition_name",
flag_values = {
"//myflags:flag1": "value1",
"//myflags:flag2": "value2",
...
},
)
```
Behavior is the same as for [built-in flags](#built-in-flags). See [here](https://github.com/bazelbuild/examples/tree/HEAD/configurations/select_on_build_setting)
for a working example.
[`--define`](/reference/command-line-reference#flag--define)
is an alternative legacy syntax for custom flags (for example
`--define foo=bar`). This can be expressed either in the
[values](/reference/be/general#config_setting.values) attribute
(`values = {"define": "foo=bar"}`) or the
[define\_values](/reference/be/general#config_setting.define_values) attribute
(`define_values = {"foo": "bar"}`). `--define` is only supported for backwards
compatibility. Prefer Starlark build settings whenever possible.
`values`, `flag_values`, and `define_values` evaluate independently. The
`config_setting` matches if all values across all of them match.
## The default condition
The built-in condition `//conditions:default` matches when no other condition
matches.
Because of the "exactly one match" rule, a configurable attribute with no match
and no default condition emits a `"no matching conditions"` error. This can
protect against silent failures from unexpected settings:
```python theme={null}
# myapp/BUILD
config_setting(
name = "x86_cpu",
values = {"cpu": "x86"},
)
cc_library(
name = "x86_only_lib",
srcs = select({
":x86_cpu": ["lib.cc"],
}),
)
```
```sh theme={null}
$ bazel build //myapp:x86_only_lib --cpu=arm
ERROR: Configurable attribute "srcs" doesn't match this configuration (would
a default condition help?).
Conditions checked:
//myapp:x86_cpu
```
For even clearer errors, you can set custom messages with `select()`'s
[`no_match_error`](#custom-error-messages) attribute.
## Platforms
While the ability to specify multiple flags on the command line provides
flexibility, it can also be burdensome to individually set each one every time
you want to build a target.
[Platforms](/extending/platforms)
let you consolidate these into simple bundles.
```python theme={null}
# myapp/BUILD
sh_binary(
name = "my_rocks",
srcs = select({
":basalt": ["pyroxene.sh"],
":marble": ["calcite.sh"],
"//conditions:default": ["feldspar.sh"],
}),
)
config_setting(
name = "basalt",
constraint_values = [
":black",
":igneous",
],
)
config_setting(
name = "marble",
constraint_values = [
":white",
":metamorphic",
],
)
# constraint_setting acts as an enum type, and constraint_value as an enum value.
constraint_setting(name = "color")
constraint_value(name = "black", constraint_setting = "color")
constraint_value(name = "white", constraint_setting = "color")
constraint_setting(name = "texture")
constraint_value(name = "smooth", constraint_setting = "texture")
constraint_setting(name = "type")
constraint_value(name = "igneous", constraint_setting = "type")
constraint_value(name = "metamorphic", constraint_setting = "type")
platform(
name = "basalt_platform",
constraint_values = [
":black",
":igneous",
],
)
platform(
name = "marble_platform",
constraint_values = [
":white",
":smooth",
":metamorphic",
],
)
```
The platform can be specified on the command line. It activates the
`config_setting`s that contain a subset of the platform's `constraint_values`,
allowing those `config_setting`s to match in `select()` expressions.
For example, in order to set the `srcs` attribute of `my_rocks` to `calcite.sh`,
you can simply run
```sh theme={null}
bazel build //my_app:my_rocks --platforms=//myapp:marble_platform
```
Without platforms, this might look something like
```sh theme={null}
bazel build //my_app:my_rocks --define color=white --define texture=smooth --define type=metamorphic
```
`select()` can also directly read `constraint_value`s:
```python theme={null}
constraint_setting(name = "type")
constraint_value(name = "igneous", constraint_setting = "type")
constraint_value(name = "metamorphic", constraint_setting = "type")
sh_binary(
name = "my_rocks",
srcs = select({
":igneous": ["igneous.sh"],
":metamorphic" ["metamorphic.sh"],
}),
)
```
This saves the need for boilerplate `config_setting`s when you only need to
check against single values.
Platforms are still under development. See the
[documentation](/concepts/platforms) for details.
## Combining `select()`s
`select` can appear multiple times in the same attribute:
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"] +
select({
":armeabi_mode": ["armeabi_src.sh"],
":x86_mode": ["x86_src.sh"],
}) +
select({
":opt_mode": ["opt_extras.sh"],
":dbg_mode": ["dbg_extras.sh"],
}),
)
```
Note: Some restrictions apply on what can be combined in the `select`s values:
* Duplicate labels can appear in different paths of the same `select`.
* Duplicate labels can *not* appear within the same path of a `select`.
* Duplicate labels can *not* appear across multiple combined `select`s (no matter what path)
`select` cannot appear inside another `select`. If you need to nest `selects`
and your attribute takes other targets as values, use an intermediate target:
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":armeabi_mode": [":armeabi_lib"],
...
}),
)
sh_library(
name = "armeabi_lib",
srcs = select({
":opt_mode": ["armeabi_with_opt.sh"],
...
}),
)
```
If you need a `select` to match when multiple conditions match, consider [AND chaining](#and-chaining).
## OR chaining
Consider the following:
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1": [":standard_lib"],
":config2": [":standard_lib"],
":config3": [":standard_lib"],
":config4": [":special_lib"],
}),
)
```
Most conditions evaluate to the same dep. But this syntax is hard to read and
maintain. It would be nice to not have to repeat `[":standard_lib"]` multiple
times.
One option is to predefine the value as a BUILD variable:
```python theme={null}
STANDARD_DEP = [":standard_lib"]
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1": STANDARD_DEP,
":config2": STANDARD_DEP,
":config3": STANDARD_DEP,
":config4": [":special_lib"],
}),
)
```
This makes it easier to manage the dependency. But it still causes unnecessary
duplication.
For more direct support, use one of the following:
### `selects.with_or`
The
[with\_or](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectswith_or)
macro in [Skylib](https://github.com/bazelbuild/bazel-skylib)'s
[`selects`](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md)
module supports `OR`ing conditions directly inside a `select`:
```python theme={null}
load("@bazel_skylib//lib:selects.bzl", "selects")
```
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = selects.with_or({
(":config1", ":config2", ":config3"): [":standard_lib"],
":config4": [":special_lib"],
}),
)
```
### `selects.config_setting_group`
The
[config\_setting\_group](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectsconfig_setting_group)
macro in [Skylib](https://github.com/bazelbuild/bazel-skylib)'s
[`selects`](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md)
module supports `OR`ing multiple `config_setting`s:
```python theme={null}
load("@bazel_skylib//lib:selects.bzl", "selects")
```
```python theme={null}
config_setting(
name = "config1",
values = {"cpu": "arm"},
)
config_setting(
name = "config2",
values = {"compilation_mode": "dbg"},
)
selects.config_setting_group(
name = "config1_or_2",
match_any = [":config1", ":config2"],
)
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1_or_2": [":standard_lib"],
"//conditions:default": [":other_lib"],
}),
)
```
Unlike `selects.with_or`, different targets can share `:config1_or_2` across
different attributes.
It's an error for multiple conditions to match unless one is an unambiguous
"specialization" of the others or they all resolve to the same value. See [here](#configurable-build-example) for details.
## AND chaining
If you need a `select` branch to match when multiple conditions match, use the
[Skylib](https://github.com/bazelbuild/bazel-skylib) macro
[config\_setting\_group](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectsconfig_setting_group):
```python theme={null}
config_setting(
name = "config1",
values = {"cpu": "arm"},
)
config_setting(
name = "config2",
values = {"compilation_mode": "dbg"},
)
selects.config_setting_group(
name = "config1_and_2",
match_all = [":config1", ":config2"],
)
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1_and_2": [":standard_lib"],
"//conditions:default": [":other_lib"],
}),
)
```
Unlike OR chaining, existing `config_setting`s can't be directly `AND`ed
inside a `select`. You have to explicitly wrap them in a `config_setting_group`.
## Custom error messages
By default, when no condition matches, the target the `select()` is attached to
fails with the error:
```sh theme={null}
ERROR: Configurable attribute "deps" doesn't match this configuration (would
a default condition help?).
Conditions checked:
//tools/cc_target_os:darwin
//tools/cc_target_os:android
```
This can be customized with the [`no_match_error`](/reference/be/functions#select)
attribute:
```python theme={null}
cc_library(
name = "my_lib",
deps = select(
{
"//tools/cc_target_os:android": [":android_deps"],
"//tools/cc_target_os:windows": [":windows_deps"],
},
no_match_error = "Please build with an Android or Windows toolchain",
),
)
```
```sh theme={null}
$ bazel build //myapp:my_lib
ERROR: Configurable attribute "deps" doesn't match this configuration: Please
build with an Android or Windows toolchain
```
## Rules compatibility
Rule implementations receive the *resolved values* of configurable
attributes. For example, given:
```python theme={null}
# myapp/BUILD
some_rule(
name = "my_target",
some_attr = select({
":foo_mode": [":foo"],
":bar_mode": [":bar"],
}),
)
```
```sh theme={null}
$ bazel build //myapp/my_target --define mode=foo
```
Rule implementation code sees `ctx.attr.some_attr` as `[":foo"]`.
Macros can accept `select()` clauses and pass them through to native
rules. But *they cannot directly manipulate them*. For example, there's no way
for a macro to convert
```python theme={null}
select({"foo": "val"}, ...)
```
to
```python theme={null}
select({"foo": "val_with_suffix"}, ...)
```
This is for two reasons.
First, macros that need to know which path a `select` will choose *cannot work*
because macros are evaluated in Bazel's [loading phase](/run/build#loading),
which occurs before flag values are known.
This is a core Bazel design restriction that's unlikely to change any time soon.
Second, macros that just need to iterate over *all* `select` paths, while
technically feasible, lack a coherent UI. Further design is necessary to change
this.
## Bazel query and cquery
Bazel [`query`](/query/guide) operates over Bazel's
[loading phase](/reference/glossary#loading-phase).
This means it doesn't know what command line flags a target uses since those
flags aren't evaluated until later in the build (in the
[analysis phase](/reference/glossary#analysis-phase)).
So it can't determine which `select()` branches are chosen.
Bazel [`cquery`](/query/cquery) operates after Bazel's analysis phase, so it has
all this information and can accurately resolve `select()`s.
Consider:
```python theme={null}
load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
```
```python theme={null}
# myapp/BUILD
string_flag(
name = "dog_type",
build_setting_default = "cat"
)
cc_library(
name = "my_lib",
deps = select({
":long": [":foo_dep"],
":short": [":bar_dep"],
}),
)
config_setting(
name = "long",
flag_values = {":dog_type": "dachshund"},
)
config_setting(
name = "short",
flag_values = {":dog_type": "pug"},
)
```
`query` overapproximates `:my_lib`'s dependencies:
```sh theme={null}
$ bazel query 'deps(//myapp:my_lib)'
//myapp:my_lib
//myapp:foo_dep
//myapp:bar_dep
```
while `cquery` shows its exact dependencies:
```sh theme={null}
$ bazel cquery 'deps(//myapp:my_lib)' --//myapp:dog_type=pug
//myapp:my_lib
//myapp:bar_dep
```
## FAQ
### Why doesn't select() work in macros?
select() *does* work in rules! See [Rules compatibility](#rules-compatibility) for
details.
The key issue this question usually means is that select() doesn't work in
*macros*. These are different than *rules*. See the
documentation on [rules](/extending/rules) and [macros](/extending/macros)
to understand the difference.
Here's an end-to-end example:
Define a rule and macro:
```python theme={null}
# myapp/defs.bzl
# Rule implementation: when an attribute is read, all select()s have already
# been resolved. So it looks like a plain old attribute just like any other.
def _impl(ctx):
name = ctx.attr.name
allcaps = ctx.attr.my_config_string.upper() # This works fine on all values.
print("My name is " + name + " with custom message: " + allcaps)
# Rule declaration:
my_custom_bazel_rule = rule(
implementation = _impl,
attrs = {"my_config_string": attr.string()},
)
# Macro declaration:
def my_custom_bazel_macro(name, my_config_string):
allcaps = my_config_string.upper() # This line won't work with select(s).
print("My name is " + name + " with custom message: " + allcaps)
```
Instantiate the rule and macro:
```python theme={null}
# myapp/BUILD
load("//myapp:defs.bzl", "my_custom_bazel_rule")
load("//myapp:defs.bzl", "my_custom_bazel_macro")
my_custom_bazel_rule(
name = "happy_rule",
my_config_string = select({
"//third_party/bazel_platforms/cpu:x86_32": "first string",
"//third_party/bazel_platforms/cpu:ppc": "second string",
}),
)
my_custom_bazel_macro(
name = "happy_macro",
my_config_string = "fixed string",
)
my_custom_bazel_macro(
name = "sad_macro",
my_config_string = select({
"//third_party/bazel_platforms/cpu:x86_32": "first string",
"//third_party/bazel_platforms/cpu:ppc": "other string",
}),
)
```
Building fails because `sad_macro` can't process the `select()`:
```sh theme={null}
$ bazel build //myapp:all
ERROR: /myworkspace/myapp/BUILD:17:1: Traceback
(most recent call last):
File "/myworkspace/myapp/BUILD", line 17
my_custom_bazel_macro(name = "sad_macro", my_config_stri..."}))
File "/myworkspace/myapp/defs.bzl", line 4, in
my_custom_bazel_macro
my_config_string.upper()
type 'select' has no method upper().
ERROR: error loading package 'myapp': Package 'myapp' contains errors.
```
Building succeeds when you comment out `sad_macro`:
```sh theme={null}
# Comment out sad_macro so it doesn't mess up the build.
$ bazel build //myapp:all
DEBUG: /myworkspace/myapp/defs.bzl:5:3: My name is happy_macro with custom message: FIXED STRING.
DEBUG: /myworkspace/myapp/hi.bzl:15:3: My name is happy_rule with custom message: FIRST STRING.
```
This is impossible to change because *by definition* macros are evaluated before
Bazel reads the build's command line flags. That means there isn't enough
information to evaluate select()s.
Macros can, however, pass `select()`s as opaque blobs to rules:
```python theme={null}
# myapp/defs.bzl
def my_custom_bazel_macro(name, my_config_string):
print("Invoking macro " + name)
my_custom_bazel_rule(
name = name + "_as_target",
my_config_string = my_config_string,
)
```
```sh theme={null}
$ bazel build //myapp:sad_macro_less_sad
DEBUG: /myworkspace/myapp/defs.bzl:23:3: Invoking macro sad_macro_less_sad.
DEBUG: /myworkspace/myapp/defs.bzl:15:3: My name is sad_macro_less_sad with custom message: FIRST STRING.
```
### Why does select() always return true?
Because *macros* (but not rules) by definition
[can't evaluate `select()`s](#faq-select-macro), any attempt to do so
usually produces an error:
```sh theme={null}
ERROR: /myworkspace/myapp/BUILD:17:1: Traceback
(most recent call last):
File "/myworkspace/myapp/BUILD", line 17
my_custom_bazel_macro(name = "sad_macro", my_config_stri..."}))
File "/myworkspace/myapp/defs.bzl", line 4, in
my_custom_bazel_macro
my_config_string.upper()
type 'select' has no method upper().
```
Booleans are a special case that fail silently, so you should be particularly
vigilant with them:
```sh theme={null}
$ cat myapp/defs.bzl
def my_boolean_macro(boolval):
print("TRUE" if boolval else "FALSE")
$ cat myapp/BUILD
load("//myapp:defs.bzl", "my_boolean_macro")
my_boolean_macro(
boolval = select({
"//third_party/bazel_platforms/cpu:x86_32": True,
"//third_party/bazel_platforms/cpu:ppc": False,
}),
)
$ bazel build //myapp:all --cpu=x86
DEBUG: /myworkspace/myapp/defs.bzl:4:3: TRUE.
$ bazel build //mypro:all --cpu=ppc
DEBUG: /myworkspace/myapp/defs.bzl:4:3: TRUE.
```
This happens because macros don't understand the contents of `select()`.
So what they're really evaluting is the `select()` object itself. According to
[Pythonic](https://docs.python.org/release/2.5.2/lib/truth.html) design
standards, all objects aside from a very small number of exceptions
automatically return true.
### Can I read select() like a dict?
Macros [can't](#faq-select-macro) evaluate select(s) because macros evaluate before
Bazel knows what the build's command line parameters are. Can they at least read
the `select()`'s dictionary to, for example, add a suffix to each value?
Conceptually this is possible, but it isn't yet a Bazel feature.
What you *can* do today is prepare a straight dictionary, then feed it into a
`select()`:
```sh theme={null}
$ cat myapp/defs.bzl
def selecty_genrule(name, select_cmd):
for key in select_cmd.keys():
select_cmd[key] += " WITH SUFFIX"
native.genrule(
name = name,
outs = [name + ".out"],
srcs = [],
cmd = "echo " + select(select_cmd + {"//conditions:default": "default"})
+ " > $@"
)
$ cat myapp/BUILD
selecty_genrule(
name = "selecty",
select_cmd = {
"//third_party/bazel_platforms/cpu:x86_32": "x86 mode",
},
)
$ bazel build //testapp:selecty --cpu=x86 && cat bazel-genfiles/testapp/selecty.out
x86 mode WITH SUFFIX
```
If you'd like to support both `select()` and native types, you can do this:
```sh theme={null}
$ cat myapp/defs.bzl
def selecty_genrule(name, select_cmd):
cmd_suffix = ""
if type(select_cmd) == "string":
cmd_suffix = select_cmd + " WITH SUFFIX"
elif type(select_cmd) == "dict":
for key in select_cmd.keys():
select_cmd[key] += " WITH SUFFIX"
cmd_suffix = select(select_cmd + {"//conditions:default": "default"})
native.genrule(
name = name,
outs = [name + ".out"],
srcs = [],
cmd = "echo " + cmd_suffix + "> $@",
)
```
### Why doesn't select() work with bind()?
First of all, do not use `bind()`. It is deprecated in favor of `alias()`.
The technical answer is that [`bind()`](/reference/be/workspace#bind) is a repo
rule, not a BUILD rule.
Repo rules do not have a specific configuration, and aren't evaluated in
the same way as BUILD rules. Therefore, a `select()` in a `bind()` can't
actually evaluate to any specific branch.
Instead, you should use [`alias()`](/reference/be/general#alias), with a `select()` in
the `actual` attribute, to perform this type of run-time determination. This
works correctly, since `alias()` is a BUILD rule, and is evaluated with a
specific configuration.
```sh theme={null}
$ cat WORKSPACE
workspace(name = "myapp")
bind(name = "openssl", actual = "//:ssl")
http_archive(name = "alternative", ...)
http_archive(name = "boringssl", ...)
$ cat BUILD
config_setting(
name = "alt_ssl",
define_values = {
"ssl_library": "alternative",
},
)
alias(
name = "ssl",
actual = select({
"//:alt_ssl": "@alternative//:ssl",
"//conditions:default": "@boringssl//:ssl",
}),
)
```
With this setup, you can pass `--define ssl_library=alternative`, and any target
that depends on either `//:ssl` or `//external:ssl` will see the alternative
located at `@alternative//:ssl`.
But really, stop using `bind()`.
### Why doesn't my select() choose what I expect?
If `//myapp:foo` has a `select()` that doesn't choose the condition you expect,
use [cquery](/query/cquery) and `bazel config` to debug:
If `//myapp:foo` is the top-level target you're building, run:
```sh theme={null}
$ bazel cquery //myapp:foo
//myapp:foo (12e23b9a2b534a)
```
If you're building some other target `//bar` that depends on
//myapp:foo somewhere in its subgraph, run:
```sh theme={null}
$ bazel cquery 'somepath(//bar, //myapp:foo)'
//bar:bar (3ag3193fee94a2)
//bar:intermediate_dep (12e23b9a2b534a)
//myapp:foo (12e23b9a2b534a)
```
The `(12e23b9a2b534a)` next to `//myapp:foo` is a *hash* of the
configuration that resolves `//myapp:foo`'s `select()`. You can inspect its
values with `bazel config`:
```sh theme={null}
$ bazel config 12e23b9a2b534a
BuildConfigurationValue 12e23b9a2b534a
Fragment com.google.devtools.build.lib.analysis.config.CoreOptions {
cpu: darwin
compilation_mode: fastbuild
...
}
Fragment com.google.devtools.build.lib.rules.cpp.CppOptions {
linkopt: [-Dfoo=bar]
...
}
...
```
Then compare this output against the settings expected by each `config_setting`.
`//myapp:foo` may exist in different configurations in the same build. See the
[cquery docs](/query/cquery) for guidance on using `somepath` to get the right
one.
Caution: To prevent restarting the Bazel server, invoke `bazel config` with the
same command line flags as the `bazel cquery`. The `config` command relies on
the configuration nodes from the still-running server of the previous command.
### Why doesn't `select()` work with platforms?
Bazel doesn't support configurable attributes checking whether a given platform
is the target platform because the semantics are unclear.
For example:
```py theme={null}
platform(
name = "x86_linux_platform",
constraint_values = [
"@platforms//cpu:x86",
"@platforms//os:linux",
],
)
cc_library(
name = "lib",
srcs = [...],
linkopts = select({
":x86_linux_platform": ["--enable_x86_optimizations"],
"//conditions:default": [],
}),
)
```
In this `BUILD` file, which `select()` should be used if the target platform has both the
`@platforms//cpu:x86` and `@platforms//os:linux` constraints, but is **not** the
`:x86_linux_platform` defined here? The author of the `BUILD` file and the user
who defined the separate platform may have different ideas.
#### What should I do instead?
Instead, define a `config_setting` that matches **any** platform with
these constraints:
```py theme={null}
config_setting(
name = "is_x86_linux",
constraint_values = [
"@platforms//cpu:x86",
"@platforms//os:linux",
],
)
cc_library(
name = "lib",
srcs = [...],
linkopts = select({
":is_x86_linux": ["--enable_x86_optimizations"],
"//conditions:default": [],
}),
)
```
This process defines specific semantics, making it clearer to users what
platforms meet the desired conditions.
#### What if I really, really want to `select` on the platform?
If your build requirements specifically require checking the platform, you
can flip the value of the `--platforms` flag in a `config_setting`:
```py theme={null}
config_setting(
name = "is_specific_x86_linux_platform",
values = {
"platforms": ["//package:x86_linux_platform"],
},
)
cc_library(
name = "lib",
srcs = [...],
linkopts = select({
":is_specific_x86_linux_platform": ["--enable_x86_optimizations"],
"//conditions:default": [],
}),
)
```
The Bazel team doesn't endorse doing this; it overly constrains your build and
confuses users when the expected condition does not match.
[BuildSettings]: /extending/config#user-defined-build-settings
# Best Practices
Source: https://bazel.build/configure/best-practices
This page assumes you are familiar with Bazel and provides guidelines and
advice on structuring your projects to take full advantage of Bazel's features.
The overall goals are:
* To use fine-grained dependencies to allow parallelism and incrementality.
* To keep dependencies well-encapsulated.
* To make code well-structured and testable.
* To create a build configuration that is easy to understand and maintain.
These guidelines are not requirements: few projects will be able to adhere to
all of them. As the man page for lint says, "A special reward will be presented
to the first person to produce a real program that produces no errors with
strict checking." However, incorporating as many of these principles as possible
should make a project more readable, less error-prone, and faster to build.
This page uses the requirement levels described in
[this RFC](https://www.ietf.org/rfc/rfc2119.txt).
## Running builds and tests
A project should always be able to run `bazel build //...` and
`bazel test //...` successfully on its stable branch. Targets that are necessary
but do not build under certain circumstances (such as,require specific build
flags, don't build on a certain platform, require license agreements) should be
tagged as specifically as possible (for example, "`requires-osx`"). This
tagging allows targets to be filtered at a more fine-grained level than the
"manual" tag and allows someone inspecting the `BUILD` file to understand what
a target's restrictions are.
## Third-party dependencies
You may declare third-party dependencies:
* Either declare them as remote repositories in the `MODULE.bazel` file.
* Or put them in a directory called `third_party/` under your workspace directory.
## Depending on binaries
Everything should be built from source whenever possible. Generally this means
that, instead of depending on a library `some-library.so`, you'd create a
`BUILD` file and build `some-library.so` from its sources, then depend on that
target.
Always building from source ensures that a build is not using a library that
was built with incompatible flags or a different architecture. There are also
some features like coverage, static analysis, or dynamic analysis that only
work on the source.
## Versioning
Prefer building all code from head whenever possible. When versions must be
used, avoid including the version in the target name (for example, `//guava`,
not `//guava-20.0`). This naming makes the library easier to update (only one
target needs to be updated). It's also more resilient to diamond dependency
issues: if one library depends on `guava-19.0` and one depends on `guava-20.0`,
you could end up with a library that tries to depend on two different versions.
If you created a misleading alias to point both targets to one `guava` library,
then the `BUILD` files are misleading.
## Using the `.bazelrc` file
For project-specific options, use the configuration file your
`workspace/.bazelrc` (see [bazelrc format](/run/bazelrc)).
If you want to support per-user options for your project that you **do not**
want to check into source control, include the line:
```
try-import %workspace%/user.bazelrc
```
(or any other file name) in your `workspace/.bazelrc`
and add `user.bazelrc` to your `.gitignore`.
The open-source
[bazelrc-preset.bzl](https://github.com/bazel-contrib/bazelrc-preset.bzl)
generates a custom bazelrc file that matches your Bazel version and provides a
preset of recommended flags.
## Packages
Every directory that contains buildable files should be a package. If a `BUILD`
file refers to files in subdirectories (such as, `srcs = ["a/b/C.java"]`) it's
a sign that a `BUILD` file should be added to that subdirectory. The longer
this structure exists, the more likely circular dependencies will be
inadvertently created, a target's scope will creep, and an increasing number
of reverse dependencies will have to be updated.
# Code coverage with Bazel
Source: https://bazel.build/configure/coverage
Bazel features a `coverage` sub-command to produce code coverage
reports on repositories that can be tested with `bazel coverage`. Due
to the idiosyncrasies of the various language ecosystems, it is not
always trivial to make this work for a given project.
This page documents the general process for creating and viewing
coverage reports, and also features some language-specific notes for
languages whose configuration is well-known. It is best read by first
reading [the general section](#creating-a-coverage-report), and then
reading about the requirements for a specific language.
While a lot of customization is possible, this document focuses on
producing and consuming [`lcov`][lcov] reports, which is currently the
most well-supported route.
## Creating a coverage report
### Preparation
The basic workflow for creating coverage reports requires the
following:
* A basic repository with test targets
* A toolchain with the language-specific code coverage tools installed
* A correct "instrumentation" configuration
The former two are language-specific and mostly straightforward,
however the latter can be more difficult for complex projects.
"Instrumentation" in this case refers to the coverage tools that are
used for a specific target. Bazel allows turning this on for a
specific subset of files using the
[`--instrumentation_filter`](/reference/command-line-reference#flag--instrumentation_filter)
flag, which specifies a filter for targets that are tested with the
instrumentation enabled. To enable instrumentation for tests, the
[`--instrument_test_targets`](/reference/command-line-reference#flag--instrument_test_targets)
flag is required.
By default, bazel tries to match the target package(s), and prints the
relevant filter as an `INFO` message.
### Running coverage
To produce a coverage report, use [`bazel coverage --combined_report=lcov [target]`](/reference/command-line-reference#coverage). This runs the
tests for the target, generating coverage reports in the lcov format
for each file.
Once finished, bazel runs an action that collects all the produced
coverage files, and merges them into one, which is then finally
created under `$(bazel info
output_path)/_coverage/_coverage_report.dat`.
Coverage reports are also produced if tests fail, though note that
this does not extend to the failed tests - only passing tests are
reported.
### Viewing coverage
The coverage report is only output in the non-human-readable `lcov`
format. From this, we can use the `genhtml` utility (part of [the lcov
project][lcov]) to produce a report that can be viewed in a web
browser:
```console theme={null}
genhtml --branch-coverage --output genhtml "$(bazel info output_path)/_coverage/_coverage_report.dat"
```
Note that `genhtml` reads the source code as well, to annotate missing
coverage in these files. For this to work, it is expected that
`genhtml` is executed in the root of the bazel project.
To view the result, simply open the `index.html` file produced in the
`genhtml` directory in any web browser.
For further help and information around the `genhtml` tool, or the
`lcov` coverage format, see [the lcov project][lcov].
## Language-specific configuration
### C++
#### Linux
C++ coverage should work out-of-the-box with the default configuration.
#### MacOS
The default value of `GCOV_PREFIX_STRIP` is almost certainly incorrect and needs
adjusting manually because the correct value depends on your setup.
When the value is incorrect, no coverage data will be found.
Example to set `GCOV_PREFIX_STRIP=10`
```
bazel coverage //foo:foo_test --test_env=GCOV_PREFIX_STRIP=10`
```
### Java
Java should work out-of-the-box with the default configuration. The
[bazel toolchains][bazel_toolchains] contain everything necessary for
remote execution, as well, including JUnit.
### Python
See the [`rules_python` coverage docs](https://rules-python.readthedocs.io/en/latest/coverage.html)
for additional steps needed to enable coverage support in Python.
[lcov]: https://github.com/linux-test-project/lcov
[bazel_toolchains]: https://github.com/bazelbuild/bazel-toolchains
# Integrating with C++ Rules
Source: https://bazel.build/configure/integrate-cpp
This page describes how to integrate with C++ rules on various levels.
## Accessing the C++ toolchain
You should use the helper functions available at
[`@rules_cc//cc:find_cc_toolchain.bzl`](https://github.com/bazelbuild/rules_cc/blob/main/cc/find_cc_toolchain.bzl)
to depend on a CC toolchain from a Starlark rule.
To depend on a C++ toolchain in your rule, set the `toolchains` parameter to
`use_cc_toolchain()`. Then, in the rule implementation, use
`find_cpp_toolchain(ctx)` to get the
[`CcToolchainInfo`](/rules/lib/providers/CcToolchainInfo). A complete working
example can be found [in the rules\_cc examples](https://github.com/bazelbuild/rules_cc/blob/main/examples/write_cc_toolchain_cpu/write_cc_toolchain_cpu.bzl).
## Generating command lines and environment variables using the C++ toolchain
Typically, you would integrate with the C++ toolchain to have the same
command line flags as C++ rules do, but without using C++ actions directly.
This is because when writing our own actions, they must behave
consistently with the C++ toolchain - for example, passing C++ command line
flags to a tool that invokes the C++ compiler behind the scenes.
C++ rules use a special way of constructing command lines based on [feature configuration](/docs/cc-toolchain-config-reference). To construct a command line,
you need the following:
* `features` and `action_configs` - these come from the `CcToolchainConfigInfo`
and encapsulated in `CcToolchainInfo`
* `FeatureConfiguration` - returned by [cc\_common.configure\_features](/rules/lib/toplevel/cc_common#configure_features)
* cc toolchain config variables - returned by
[cc\_common.create\_compile\_variables](/rules/lib/toplevel/cc_common#create_compile_variables)
or
[cc\_common.create\_link\_variables](/rules/lib/toplevel/cc_common#create_link_variables).
There still are tool-specific getters, such as
[compiler\_executable](/rules/lib/providers/CcToolchainInfo#compiler_executable).
Prefer `get_tool_for_action` over these, as tool-specific getters will
eventually be removed.
A complete working example can be found
[in the rules\_cc examples](https://github.com/bazelbuild/rules_cc/blob/main/examples/my_c_compile/my_c_compile.bzl).
## Implementing Starlark rules that depend on C++ rules and/or that C++ rules can depend on
Most C++ rules provide
[`CcInfo`](/rules/lib/providers/CcInfo),
a provider containing [`CompilationContext`](/rules/lib/builtins/CompilationContext)
and
[`LinkingContext`](/rules/lib/builtins/LinkingContext).
Through these it is possible to access information such as all transitive headers
or libraries to link. From `CcInfo` and from the `CcToolchainInfo` custom
Starlark rules should be able to get all the information they need.
If a custom Starlark rule provides `CcInfo`, it's a signal to the C++ rules that
they can also depend on it. Be careful, however - if you only need to propagate
`CcInfo` through the graph to the binary rule that then makes use of it, wrap
`CcInfo` in a different provider. For example, if `java_library` rule wanted
to propagate native dependencies up to the `java_binary`, it shouldn't provide
`CcInfo` directly (`cc_binary` depending on `java_library` doesn't make sense),
it should wrap it in, for example, `JavaCcInfo`.
A complete working example can be found
[in the rules\_cc examples](https://github.com/bazelbuild/rules_cc/blob/main/examples/my_c_archive/my_c_archive.bzl).
## Reusing logic and actions of C++ rules
*Not stable yet; This section will be updated once the API stabilizes. Follow
[#4570](https://github.com/bazelbuild/bazel/issues/4570) for up-to-date
information.*
# Using Bazel on Windows
Source: https://bazel.build/configure/windows
This page covers Best Practices for using Bazel on Windows. For installation
instructions, see [Install Bazel on Windows](/install/windows).
## Known issues
Windows-related Bazel issues are marked with the "area-Windows" label on GitHub.
[GitHub-Windows].
[GitHub-Windows]: https://github.com/bazelbuild/bazel/issues?q=is%3Aopen+is%3Aissue+label%3Aarea-Windows
## Best practices
### Avoid long path issues
Some tools have the [Maximum Path Length Limitation](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file#maximum-path-length-limitation) on Windows, including the MSVC compiler.
To avoid hitting this issue, you can specify a short output directory for Bazel by the [--output\_user\_root](/reference/command-line-reference#flag--output_user_root) flag.
For example, add the following line to your bazelrc file:
```none theme={null}
startup --output_user_root=C:/tmp
```
### Enable symlink support
Some features require Bazel to be able to create file symlinks on Windows,
either by enabling
[Developer Mode](https://docs.microsoft.com/en-us/windows/uwp/get-started/enable-your-device-for-development)
(on Windows 10 version 1703 or newer), or by running Bazel as an administrator.
This enables the following features:
* [--windows\_enable\_symlinks](/reference/command-line-reference#flag--windows_enable_symlinks)
* [--enable\_runfiles](/reference/command-line-reference#flag--enable_runfiles)
To make it easier, add the following lines to your bazelrc file:
```none theme={null}
startup --windows_enable_symlinks
build --enable_runfiles
```
**Note**: Creating symlinks on Windows is an expensive operation. The `--enable_runfiles` flag can potentially create a large amount of file symlinks. Only enable this feature when you need it.
### Running Bazel: MSYS2 shell vs. command prompt vs. PowerShell
**Recommendation:** Run Bazel from the command prompt (`cmd.exe`) or from
PowerShell.
As of 2020-01-15, **do not** run Bazel from `bash` -- either
from MSYS2 shell, or Git Bash, or Cygwin, or any other Bash variant. While Bazel
may work for most use cases, some things are broken, like
[interrupting the build with Ctrl+C from MSYS2](https://github.com/bazelbuild/bazel/issues/10573)).
Also, if you choose to run under MSYS2, you need to disable MSYS2's
automatic path conversion, otherwise MSYS will convert command line arguments
that *look like* Unix paths (such as `//foo:bar`) into Windows paths. See
[this StackOverflow answer](https://stackoverflow.com/a/49004265/7778502)
for details.
### Using Bazel without Bash (MSYS2)
#### Using bazel build without Bash
Bazel versions before 1.0 used to require Bash to build some rules.
Starting with Bazel 1.0, you can build any rule without Bash unless it is a:
* `genrule`, because genrules execute Bash commands
* `sh_binary` or `sh_test` rule, because these inherently need Bash
* Starlark rule that uses `ctx.actions.run_shell()` or `ctx.resolve_command()`
However, `genrule` is often used for simple tasks like
[copying a file](https://github.com/bazelbuild/bazel-skylib/blob/main/rules/copy_file.bzl)
or [writing a text file](https://github.com/bazelbuild/bazel-skylib/blob/main/rules/write_file.bzl).
Instead of using `genrule` (and depending on Bash) you may find a suitable rule
in the
[bazel-skylib repository](https://github.com/bazelbuild/bazel-skylib/tree/main/rules).
When built on Windows, **these rules do not require Bash**.
#### Using bazel test without Bash
Bazel versions before 1.0 used to require Bash to `bazel test` anything.
Starting with Bazel 1.0, you can test any rule without Bash, except when:
* you use `--run_under`
* the test rule itself requires Bash (because its executable is a shell script)
#### Using bazel run without Bash
Bazel versions before 1.0 used to require Bash to `bazel run` anything.
Starting with Bazel 1.0, you can run any rule without Bash, except when:
* you use `--run_under` or `--script_path`
* the test rule itself requires Bash (because its executable is a shell script)
#### Using sh\_binary and sh\_\* rules, and ctx.actions.run\_shell() without Bash
You need Bash to build and test `sh_*` rules, and to build and test Starlark
rules that use `ctx.actions.run_shell()` and `ctx.resolve_command()`. This
applies not only to rules in your project, but to rules in any of the external
repositories your project depends on (even transitively).
In the future, there may be an option to use Windows Subsystem for
Linux (WSL) to build these rules, but currently it is not a priority for
the Bazel-on-Windows subteam.
### Setting environment variables
Environment variables you set in the Windows Command Prompt (`cmd.exe`) are only
set in that command prompt session. If you start a new `cmd.exe`, you need to
set the variables again. To always set the variables when `cmd.exe` starts, you
can add them to the User variables or System variables in the `Control Panel >
System Properties > Advanced > Environment Variables...` dialog box.
## Build on Windows
### Build C++ with MSVC
To build C++ targets with MSVC, you need:
* [The Visual C++ compiler](/install/windows#install-vc).
* (Optional) The `BAZEL_VC` and `BAZEL_VC_FULL_VERSION` environment variable.
Bazel automatically detects the Visual C++ compiler on your system.
To tell Bazel to use a specific VC installation, you can set the
following environment variables:
For Visual Studio 2017 and 2019, set one of `BAZEL_VC`. Additionally you may also set `BAZEL_VC_FULL_VERSION`.
* `BAZEL_VC` the Visual C++ Build Tools installation directory
```
set BAZEL_VC=C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC
```
* `BAZEL_VC_FULL_VERSION` (Optional) Only for Visual Studio 2017 and 2019, the full version
number of your Visual C++ Build Tools. You can choose the exact Visual C++ Build Tools
version via `BAZEL_VC_FULL_VERSION` if more than one version are installed, otherwise Bazel
will choose the latest version.
```
set BAZEL_VC_FULL_VERSION=14.16.27023
```
For Visual Studio 2015 or older, set `BAZEL_VC`. (`BAZEL_VC_FULL_VERSION` is not supported.)
* `BAZEL_VC` the Visual C++ Build Tools installation directory
```
set BAZEL_VC=C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC
```
* The [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-10-sdk).
The Windows SDK contains header files and libraries you need when building
Windows applications, including Bazel itself. By default, the latest Windows SDK installed will
be used. You also can specify Windows SDK version by setting `BAZEL_WINSDK_FULL_VERSION`. You
can use a full Windows 10 SDK number such as 10.0.10240.0, or specify 8.1 to use the Windows 8.1
SDK (only one version of Windows 8.1 SDK is available). Please make sure you have the specified
Windows SDK installed.
**Requirement**: This is supported with VC 2017 and 2019. The standalone VC 2015 Build Tools doesn't
support selecting Windows SDK, you'll need the full Visual Studio 2015 installation, otherwise
`BAZEL_WINSDK_FULL_VERSION` will be ignored.
```
set BAZEL_WINSDK_FULL_VERSION=10.0.10240.0
```
If everything is set up, you can build a C++ target now!
Try building a target from one of our [sample projects](https://github.com/bazelbuild/bazel/tree/master/examples):
```
bazel build //examples/cpp:hello-worldbazel-bin\examples\cpp\hello-world.exe
```
By default, the built binaries target x64 architecture. To build for ARM64
architecture, use
```none theme={null}
--platforms=//:windows_arm64 --extra_toolchains=@local_config_cc//:cc-toolchain-arm64_windows
```
You can introduce `@local_config_cc` in `MODULE.bazel` with
```python theme={null}
bazel_dep(name = "rules_cc", version = "0.1.1")
cc_configure = use_extension("@rules_cc//cc:extensions.bzl", "cc_configure_extension")
use_repo(cc_configure, "local_config_cc")
```
To build and use Dynamically Linked Libraries (DLL files), see [this example](https://github.com/bazelbuild/bazel/tree/master/examples/windows/dll).
**Command Line Length Limit**: To prevent the
[Windows command line length limit issue](https://github.com/bazelbuild/bazel/issues/5163),
enable the compiler parameter file feature via `--features=compiler_param_file`.
### Build C++ with Clang
From 0.29.0, Bazel supports building with LLVM's MSVC-compatible compiler driver (`clang-cl.exe`).
**Requirement**: To build with Clang, you have to install **both**
[LLVM](http://releases.llvm.org/download.html) and Visual C++ Build tools,
because although you use `clang-cl.exe` as compiler, you still need to link to
Visual C++ libraries.
Bazel can automatically detect LLVM installation on your system, or you can explicitly tell
Bazel where LLVM is installed by `BAZEL_LLVM`.
* `BAZEL_LLVM` the LLVM installation directory
```posix-terminal theme={null}
set BAZEL_LLVM=C:\Program Files\LLVM
```
To enable the Clang toolchain, the configuration depends on your Bazel version
and whether you are using Bzlmod or WORKSPACE.
***
**Bazel 8 and newer:**
* **Using Bzlmod (Recommended):**
1. Ensure you have `rules_cc` loaded in your `MODULE.bazel` and configure
the CC toolchains:
```python theme={null}
bazel_dep(name = "rules_cc", version = "0.0.17") # Or newer
cc_configure = use_extension("@rules_cc//cc:extensions.bzl", "cc_configure_extension")
use_repo(cc_configure, "local_config_cc")
```
2. Define a `platform` target in a BUILD file (e.g., the root BUILD file):
```python theme={null}
platform(
name = "x64_windows-clang-cl",
constraint_values = [
"@platforms//cpu:x86_64",
"@platforms//os:windows",
"@bazel_tools//tools/cpp:clang-cl", # Alias to the @rules_cc constraint in Bazel 8+
],
)
```
3. Enable the toolchain using these flags:
```bash theme={null}
--extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows-clang-cl --extra_execution_platforms=//:x64_windows-clang-cl
```
* **Using WORKSPACE:**
1. Load the `rules_cc` dependencies and toolchains in your `WORKSPACE` file
:
```python theme={null}
load("@rules_cc//cc:repositories.bzl", "rules_cc_dependencies", "rules_cc_toolchains")
rules_cc_dependencies()
rules_cc_toolchains()
```
2. Define a `platform` target in a BUILD file (e.g., the root BUILD file):
```python theme={null}
platform(
name = "x64_windows-clang-cl",
constraint_values = [
"@platforms//cpu:x86_64",
"@platforms//os:windows",
"@bazel_tools//tools/cpp:clang-cl", # Alias to the @rules_cc constraint in Bazel 8+
],
)
```
3. Enable the toolchain using these flags:
```bash theme={null}
--extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows-clang-cl --extra_execution_platforms=//:x64_windows-clang-cl
```
***
**Bazel 7:**
**Note:** In Bazel 7, `@bazel_tools//tools/cpp:clang-cl` is *not* an alias for
the `@rules_cc` constraint. To correctly use `clang-cl` with `rules_cc` in Bazel
7, you must reference a constraint within the `@rules_cc` repository. The label
`@rules_cc//cc/private/toolchain:clang-cl` is technically private but is
necessary for consistent behavior between WORKSPACE and Bzlmod setups in Bazel
7\.
* **Using Bzlmod:**
1. Setup `MODULE.bazel` as in the Bazel 8 example.
2. Define the `platform` target using the `@rules_cc` private constraint:
```python theme={null}
platform(
name = "x64_windows-clang-cl",
constraint_values = [
"@platforms//cpu:x86_64",
"@platforms//os:windows",
"@rules_cc//cc/private/toolchain:clang-cl", # Necessary for Bazel 7
],
)
```
3. Enable the toolchain using these flags:
```bash theme={null}
--extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows-clang-cl --extra_execution_platforms=//:x64_windows-clang-cl
```
* **Using WORKSPACE:**
1. Load the `rules_cc` dependencies and toolchains in your `WORKSPACE` file
:
```python theme={null}
load("@rules_cc//cc:repositories.bzl", "rules_cc_dependencies", "rules_cc_toolchains")
rules_cc_dependencies()
rules_cc_toolchains()
```
2. Define the `platform` target using the `@rules_cc` private constraint:
```python theme={null}
platform(
name = "x64_windows-clang-cl",
constraint_values = [
"@platforms//cpu:x86_64",
"@platforms//os:windows",
"@rules_cc//cc/private/toolchain:clang-cl", # Necessary for Bazel 7
],
)
```
3. Enable the toolchain using these flags:
```bash theme={null}
--extra_toolchains=@local_config_cc//:cc-toolchain-x64_windows-clang-cl --extra_execution_platforms=//:x64_windows-clang-cl
```
***
**Bazel 0.29 to 6.x:**
* Enable the Clang toolchain by
a build flag `--compiler=clang-cl`.
* If your build sets the flag
[--incompatible\_enable\_cc\_toolchain\_resolution](https://github.com/bazelbuild/bazel/issues/7260)
to `true`, then use the approach for Bazel 7.0.0.
**Bazel 0.28 and older:**
* Clang is not supported.
### Build Java
To build Java targets, you need:
* [The Java SE Development Kit](/install/windows#install-jdk)
On Windows, Bazel builds two output files for `java_binary` rules:
* a `.jar` file
* a `.exe` file that can set up the environment for the JVM and run the binary
Try building a target from one of our [sample projects](https://github.com/bazelbuild/bazel/tree/master/examples):
```
bazel build //examples/java-native/src/main/java/com/example/myproject:hello-worldbazel-bin\examples\java-native\src\main\java\com\example\myproject\hello-world.exe
```
### Build Python
To build Python targets, you need:
* The [Python interpreter](/install/windows#install-python)
On Windows, Bazel builds two output files for `py_binary` rules:
* a self-extracting zip file
* an executable file that can launch the Python interpreter with the
self-extracting zip file as the argument
You can either run the executable file (it has a `.exe` extension) or you can run
Python with the self-extracting zip file as the argument.
Try building a target from one of our [sample projects](https://github.com/bazelbuild/bazel/tree/master/examples):
```
bazel build //examples/py_native:binbazel-bin\examples\py_native\bin.exepython bazel-bin\examples\py_native\bin.zip
```
If you are interested in details about how Bazel builds Python targets on
Windows, check out this [design doc](https://github.com/bazelbuild/bazel-website/blob/master/designs/_posts/2016-09-05-build-python-on-windows.md).
# Android Build Performance
Source: https://bazel.build/docs/android-build-performance
This page contains information on optimizing build performance for Android
apps specifically. For general build performance optimization with Bazel, see
[Optimizing Performance](/rules/performance).
## Recommended flags
The flags are in the
[`bazelrc` configuration syntax](/run/bazelrc#bazelrc-syntax-semantics), so
they can be pasted directly into a `bazelrc` file and invoked with
`--config=` on the command line.
**Profiling performance**
Bazel writes a JSON trace profile by default to a file called
`command.profile.gz` in Bazel's output base.
See the [JSON Profile documentation](/rules/performance#performance-profiling) for
how to read and interact with the profile.
**Persistent workers for Android build actions**.
A subset of Android build actions has support for
[persistent workers](https://blog.bazel.build/2015/12/10/java-workers.html).
These actions' mnemonics are:
* DexBuilder
* Javac
* Desugar
* AaptPackage
* AndroidResourceParser
* AndroidResourceValidator
* AndroidResourceCompiler
* RClassGenerator
* AndroidResourceLink
* AndroidAapt2
* AndroidAssetMerger
* AndroidResourceMerger
* AndroidCompiledResourceMerger
Enabling workers can result in better build performance by saving on JVM
startup costs from invoking each of these tools, but at the cost of increased
memory usage on the system by persisting them.
To enable workers for these actions, apply these flags with
`--config=android_workers` on the command line:
```
build:android_workers --strategy=DexBuilder=worker
build:android_workers --strategy=Javac=worker
build:android_workers --strategy=Desugar=worker
# A wrapper flag for these resource processing actions:
# - AndroidResourceParser
# - AndroidResourceValidator
# - AndroidResourceCompiler
# - RClassGenerator
# - AndroidResourceLink
# - AndroidAapt2
# - AndroidAssetMerger
# - AndroidResourceMerger
# - AndroidCompiledResourceMerger
build:android_workers --persistent_android_resource_processor
```
The default number of persistent workers created per action is `4`. We have
[measured improved build performance](https://github.com/bazelbuild/bazel/issues/8586#issuecomment-500070549)
by capping the number of instances for each action to `1` or `2`, although this
may vary depending on the system Bazel is running on, and the project being
built.
To cap the number of instances for an action, apply these flags:
```
build:android_workers --worker_max_instances=DexBuilder=2
build:android_workers --worker_max_instances=Javac=2
build:android_workers --worker_max_instances=Desugar=2
build:android_workers --worker_max_instances=AaptPackage=2
# .. and so on for each action you're interested in.
```
**Using AAPT2**
[`aapt2`](https://developer.android.com/studio/command-line/aapt2) has improved
performance over `aapt` and also creates smaller APKs. To use `aapt2`, use the
`--android_aapt=aapt2` flag or set `aapt2` on the `aapt_version` on
`android_binary` and `android_local_test`.
**SSD optimizations**
The `--experimental_multi_threaded_digest` flag is useful for optimizing digest
computation on SSDs.
# Android Instrumentation Tests
Source: https://bazel.build/docs/android-instrumentation-test
*If you're new to Bazel, start with the [Building Android with Bazel](/start/android-app) tutorial.*
**Figure 1.** Running parallel Android instrumentation tests.
[`android_instrumentation_test`](/reference/be/android#android_instrumentation_test)
allows developers to test their apps on Android emulators and devices.
It utilizes real Android framework APIs and the Android Test Library.
For hermeticity and reproducibility, Bazel creates and launches Android
emulators in a sandbox, ensuring that tests always run from a clean state. Each
test gets an isolated emulator instance, allowing tests to run in parallel
without passing states between them.
For more information on Android instrumentation tests, check out the [Android developer documentation](https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html).
Please file issues in the [GitHub issue tracker](https://github.com/bazelbuild/bazel/issues).
## How it works
When you run `bazel test` on an `android_instrumentation_test` target for the
first time, Bazel performs the following steps:
1. Builds the test APK, APK under test, and their transitive dependencies
2. Creates, boots, and caches clean emulator states
3. Starts the emulator
4. Installs the APKs
5. Runs tests utilizing the [Android Test Orchestrator](https://developer.android.com/training/testing/junit-runner.html#using-android-test-orchestrator)
6. Shuts down the emulator
7. Reports the results
In subsequent test runs, Bazel boots the emulator from the clean, cached state
created in step 2, so there are no leftover states from previous runs. Caching
emulator state also speeds up test runs.
## Prerequisites
Ensure your environment satisfies the following prerequisites:
* **Linux**. Tested on Ubuntu 16.04, and 18.04.
* **Bazel 0.12.0** or later. Verify the version by running `bazel info release`.
```posix-terminal theme={null}
bazel info release
```
This results in output similar to the following:
```none theme={null}
release 4.1.0
```
* **KVM**. Bazel requires emulators to have [hardware acceleration](https://developer.android.com/studio/run/emulator-acceleration.html#accel-check)
with KVM on Linux. You can follow these
[installation instructions](https://help.ubuntu.com/community/KVM/Installation)
for Ubuntu.
To verify that KVM has the correct configuration, run:
```posix-terminal theme={null}
apt-get install cpu-checker && kvm-ok
```
If it prints the following message, you have the correct configuration:
```none theme={null}
INFO: /dev/kvm exists
KVM acceleration can be used
```
* **Xvfb**. To run headless tests (for example, on CI servers), Bazel requires
the [X virtual framebuffer](https://www.x.org/archive/X11R7.6/doc/man/man1/Xvfb.1.xhtml).
To install it, run:
```posix-terminal theme={null}
apt-get install xvfb
```
Verify that `Xvfb` is installed correctly and is installed at `/usr/bin/Xvfb`
by running:
```posix-terminal theme={null}
which Xvfb
```
The output is the following:
```
/usr/bin/Xvfb
```
* **32-bit Libraries**. Some of the binaries used by the test infrastructure are
32-bit, so on 64-bit machines, ensure that 32-bit binaries can be run. For
Ubuntu, install these 32-bit libraries:
```posix-terminal theme={null}
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386
```
## Getting started
Here is a typical target dependency graph of an `android_instrumentation_test`:
**Figure 2.** Target dependency graph of an `android_instrumentation_test`.
### BUILD file
The graph translates into a `BUILD` file like this:
```python theme={null}
android_instrumentation_test(
name = "my_test",
test_app = ":my_test_app",
target_device = "@android_test_support//tools/android/emulated_devices/generic_phone:android_23_x86",
)
# Test app and library
android_binary(
name = "my_test_app",
instruments = ":my_app",
manifest = "AndroidTestManifest.xml",
deps = [":my_test_lib"],
# ...
)
android_library(
name = "my_test_lib",
srcs = glob(["javatest/**/*.java"]),
deps = [
":my_app_lib",
"@maven//:androidx_test_core",
"@maven//:androidx_test_runner",
"@maven//:androidx_test_espresso_espresso_core",
],
# ...
)
# Target app and library under test
android_binary(
name = "my_app",
manifest = "AndroidManifest.xml",
deps = [":my_app_lib"],
# ...
)
android_library(
name = "my_app_lib",
srcs = glob(["java/**/*.java"]),
deps = [
"@maven//:androidx_appcompat_appcompat",
"@maven//:androidx_annotation_annotation",
]
# ...
)
```
The main attributes of the rule `android_instrumentation_test` are:
* `test_app`: An `android_binary` target. This target contains test code and
dependencies like Espresso and UIAutomator. The selected `android_binary`
target is required to specify an `instruments` attribute pointing to another
`android_binary`, which is the app under test.
* `target_device`: An `android_device` target. This target describes the
specifications of the Android emulator which Bazel uses to create, launch and
run the tests. See the [section on choosing an Android device](#android-device-target) for more information.
The test app's `AndroidManifest.xml` must include [an `` tag](https://developer.android.com/studio/test/#configure_instrumentation_manifest_settings).
This tag must specify the attributes for the **package of the target app** and
the **fully qualified class name of the instrumentation test runner**,
`androidx.test.runner.AndroidJUnitRunner`.
Here is an example `AndroidTestManifest.xml` for the test app:
```xml theme={null}
```
### WORKSPACE dependencies
In order to use this rule, your project needs to depend on these external
repositories:
* `@androidsdk`: The Android SDK. Download this through Android Studio.
* `@android_test_support`: Hosts the test runner, emulator launcher, and
`android_device` targets. You can find the [latest release here](https://github.com/android/android-test/releases).
Enable these dependencies by adding the following lines to your `WORKSPACE`
file:
```python theme={null}
# Android SDK
android_sdk_repository(
name = "androidsdk",
path = "/path/to/sdk", # or set ANDROID_HOME
)
# Android Test Support
ATS_COMMIT = "$COMMIT_HASH"
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "android_test_support",
strip_prefix = "android-test-%s" % ATS_COMMIT,
urls = ["https://github.com/android/android-test/archive/%s.tar.gz" % ATS_COMMIT],
)
load("@android_test_support//:repo.bzl", "android_test_repositories")
android_test_repositories()
```
## Maven dependencies
For managing dependencies on Maven artifacts from repositories, such as [Google Maven](https://maven.google.com) or [Maven Central](https://central.maven.org),
you should use a Maven resolver, such as
[`rules_jvm_external`](https://github.com/bazelbuild/rules_jvm_external).
The rest of this page shows how to use `rules_jvm_external` to
resolve and fetch dependencies from Maven repositories.
## Choosing an android\_device target
`android_instrumentation_test.target_device` specifies which Android device to
run the tests on. These `android_device` targets are defined in
[`@android_test_support`](https://github.com/google/android-testing-support-library/tree/master/tools/android/emulated_devices).
For example, you can query for the sources for a particular target by running:
```posix-terminal theme={null}
bazel query --output=build @android_test_support//tools/android/emulated_devices/generic_phone:android_23_x86
```
Which results in output that looks similar to:
```python theme={null}
# .../external/android_test_support/tools/android/emulated_devices/generic_phone/BUILD:43:1
android_device(
name = "android_23_x86",
visibility = ["//visibility:public"],
tags = ["requires-kvm"],
generator_name = "generic_phone",
generator_function = "make_device",
generator_location = "tools/android/emulated_devices/generic_phone/BUILD:43",
vertical_resolution = 800,
horizontal_resolution = 480,
ram = 2048,
screen_density = 240,
cache = 32,
vm_heap = 256,
system_image = "@android_test_support//tools/android/emulated_devices/generic_phone:android_23_x86_images",
default_properties = "@android_test_support//tools/android/emulated_devices/generic_phone:_android_23_x86_props",
)
```
The device target names use this template:
```
@android_test_support//tools/android/emulated_devices/device_type:system_api_level_x86_qemu2
```
In order to launch an `android_device`, the `system_image` for the selected API
level is required. To download the system image, use Android SDK's
`tools/bin/sdkmanager`. For example, to download the system image for
`generic_phone:android_23_x86`, run `$sdk/tools/bin/sdkmanager
"system-images;android-23;default;x86"`.
To see the full list of supported `android_device` targets in
`@android_test_support`, run the following command:
```posix-terminal theme={null}
bazel query 'filter("x86_qemu2$", kind(android_device, @android_test_support//tools/android/emulated_devices/...:*))'
```
Bazel currently supports x86-based emulators only. For better performance, use
`QEMU2` `android_device` targets instead of `QEMU` ones.
## Running tests
To run tests, add these lines to your project's
`project root:/.bazelrc` file.
```
# Configurations for testing with Bazel
# Select a configuration by running
# `bazel test //my:target --config={headless, gui, local_device}`
# Headless instrumentation tests (No GUI)
test:headless --test_arg=--enable_display=false
# Graphical instrumentation tests. Ensure that $DISPLAY is set.
test:gui --test_env=DISPLAY
test:gui --test_arg=--enable_display=true
# Testing with a local emulator or device. Ensure that `adb devices` lists the
# device.
# Run tests serially.
test:local_device --test_strategy=exclusive
# Use the local device broker type, as opposed to WRAPPED_EMULATOR.
test:local_device --test_arg=--device_broker_type=LOCAL_ADB_SERVER
# Uncomment and set $device_id if there is more than one connected device.
# test:local_device --test_arg=--device_serial_number=$device_id
```
Then, use one of the configurations to run tests:
* `bazel test //my/test:target --config=gui`
* `bazel test //my/test:target --config=headless`
* `bazel test //my/test:target --config=local_device`
Use **only one configuration** or tests will fail.
### Headless testing
With `Xvfb`, it is possible to test with emulators without the graphical
interface, also known as headless testing. To disable the graphical interface
when running tests, pass the test argument `--enable_display=false` to Bazel:
```posix-terminal theme={null}
bazel test //my/test:target --test_arg=--enable_display=false
```
### GUI testing
If the `$DISPLAY` environment variable is set, it's possible to enable the
graphical interface of the emulator while the test is running. To do this, pass
these test arguments to Bazel:
```posix-terminal theme={null}
bazel test //my/test:target --test_arg=--enable_display=true --test_env=DISPLAY
```
### Testing with a local emulator or device
Bazel also supports testing directly on a locally launched emulator or connected
device. Pass the flags
`--test_strategy=exclusive` and
`--test_arg=--device_broker_type=LOCAL_ADB_SERVER` to enable local testing mode.
If there is more than one connected device, pass the flag
`--test_arg=--device_serial_number=$device_id` where `$device_id` is the id of
the device/emulator listed in `adb devices`.
## Sample projects
If you are looking for canonical project samples, see the [Android testing samples](https://github.com/googlesamples/android-testing#experimental-bazel-support)
for projects using Espresso and UIAutomator.
## Espresso setup
If you write UI tests with [Espresso](https://developer.android.com/training/testing/espresso/)
(`androidx.test.espresso`), you can use the following snippets to set up your
Bazel workspace with the list of commonly used Espresso artifacts and their
dependencies:
```
androidx.test.espresso:espresso-core
androidx.test:rules
androidx.test:runner
javax.inject:javax.inject
org.hamcrest:java-hamcrest
junit:junit
```
One way to organize these dependencies is to create a `//:test_deps` shared
library in your `project root/BUILD.bazel` file:
```python theme={null}
java_library(
name = "test_deps",
visibility = ["//visibility:public"],
exports = [
"@maven//:androidx_test_espresso_espresso_core",
"@maven//:androidx_test_rules",
"@maven//:androidx_test_runner",
"@maven//:javax_inject_javax_inject"
"@maven//:org_hamcrest_java_hamcrest",
"@maven//:junit_junit",
],
)
```
Then, add the required dependencies in `project root/WORKSPACE`:
```python theme={null}
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
RULES_JVM_EXTERNAL_TAG = "2.8"
RULES_JVM_EXTERNAL_SHA = "79c9850690d7614ecdb72d68394f994fef7534b292c4867ce5e7dec0aa7bdfad"
http_archive(
name = "rules_jvm_external",
strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG,
sha256 = RULES_JVM_EXTERNAL_SHA,
url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG,
)
load("@rules_jvm_external//:defs.bzl", "maven_install")
maven_install(
artifacts = [
"junit:junit:4.12",
"javax.inject:javax.inject:1",
"org.hamcrest:java-hamcrest:2.0.0.0"
"androidx.test.espresso:espresso-core:3.1.1",
"androidx.test:rules:aar:1.1.1",
"androidx.test:runner:aar:1.1.1",
],
repositories = [
"https://maven.google.com",
"https://repo1.maven.org/maven2",
],
)
```
Finally, in your test `android_binary` target, add the `//:test_deps`
dependency:
```python theme={null}
android_binary(
name = "my_test_app",
instruments = "//path/to:app",
deps = [
"//:test_deps",
# ...
],
# ...
)
```
## Tips
### Reading test logs
Use `--test_output=errors` to print logs for failing tests, or
`--test_output=all` to print all test output. If you're looking for an
individual test log, go to
`$PROJECT_ROOT/bazel-testlogs/path/to/InstrumentationTestTargetName`.
For example, the test logs for `BasicSample` canonical project are in
`bazel-testlogs/ui/espresso/BasicSample/BasicSampleInstrumentationTest`, run:
```posix-terminal theme={null}
tree bazel-testlogs/ui/espresso/BasicSample/BasicSampleInstrumentationTest
```
This results in the following output:
```none theme={null}
$ tree bazel-testlogs/ui/espresso/BasicSample/BasicSampleInstrumentationTest
.
├── adb.409923.log
├── broker_logs
│ ├── aapt_binary.10.ok.txt
│ ├── aapt_binary.11.ok.txt
│ ├── adb.12.ok.txt
│ ├── adb.13.ok.txt
│ ├── adb.14.ok.txt
│ ├── adb.15.fail.txt
│ ├── adb.16.ok.txt
│ ├── adb.17.fail.txt
│ ├── adb.18.ok.txt
│ ├── adb.19.fail.txt
│ ├── adb.20.ok.txt
│ ├── adb.21.ok.txt
│ ├── adb.22.ok.txt
│ ├── adb.23.ok.txt
│ ├── adb.24.fail.txt
│ ├── adb.25.ok.txt
│ ├── adb.26.fail.txt
│ ├── adb.27.ok.txt
│ ├── adb.28.fail.txt
│ ├── adb.29.ok.txt
│ ├── adb.2.ok.txt
│ ├── adb.30.ok.txt
│ ├── adb.3.ok.txt
│ ├── adb.4.ok.txt
│ ├── adb.5.ok.txt
│ ├── adb.6.ok.txt
│ ├── adb.7.ok.txt
│ ├── adb.8.ok.txt
│ ├── adb.9.ok.txt
│ ├── android_23_x86.1.ok.txt
│ └── exec-1
│ ├── adb-2.txt
│ ├── emulator-2.txt
│ └── mksdcard-1.txt
├── device_logcat
│ └── logcat1635880625641751077.txt
├── emulator_itCqtc.log
├── outputs.zip
├── pipe.log.txt
├── telnet_pipe.log.txt
└── tmpuRh4cy
├── watchdog.err
└── watchdog.out
4 directories, 41 files
```
### Reading emulator logs
The emulator logs for `android_device` targets are stored in the `/tmp/`
directory with the name `emulator_xxxxx.log`, where `xxxxx` is a
randomly-generated sequence of characters.
Use this command to find the latest emulator log:
```posix-terminal theme={null}
ls -1t /tmp/emulator_*.log | head -n 1
```
### Testing against multiple API levels
If you would like to test against multiple API levels, you can use a list
comprehension to create test targets for each API level. For example:
```python theme={null}
API_LEVELS = [
"19",
"20",
"21",
"22",
]
[android_instrumentation_test(
name = "my_test_%s" % API_LEVEL,
test_app = ":my_test_app",
target_device = "@android_test_support//tools/android/emulated_devices/generic_phone:android_%s_x86_qemu2" % API_LEVEL,
) for API_LEVEL in API_LEVELS]
```
## Known issues
* [Forked adb server processes are not terminated after tests](https://github.com/bazelbuild/bazel/issues/4853)
* While APK building works on all platforms (Linux, macOS, Windows), testing
only works on Linux.
* Even with `--config=local_adb`, users still need to specify
`android_instrumentation_test.target_device`.
* If using a local device or emulator, Bazel does not uninstall the APKs after
the test. Clean the packages by running this command:
```posix-terminal theme={null}
adb shell pm list
packages com.example.android.testing | cut -d ':' -f 2 | tr -d '\r' | xargs
-L1 -t adb uninstall
```
# Using the Android Native Development Kit with Bazel
Source: https://bazel.build/docs/android-ndk
*If you're new to Bazel, please start with the [Building Android with Bazel](/start/android-app) tutorial.*
## Overview
Bazel can run in many different build configurations, including several that use
the Android Native Development Kit (NDK) toolchain. This means that normal
`cc_library` and `cc_binary` rules can be compiled for Android directly within
Bazel. Bazel accomplishes this by using the `android_ndk_repository` repository
rule and its related bzlmod extension.
For general Android
compilation, use [`rules_android`](https://github.com/bazelbuild/rules_android).
This tutorial demonstrates how to integrate C++ library dependencies into
Android apps and uses
[`rules_android_ndk`](https://github.com/bazelbuild/rules_android_ndk) for NDK
toolchain discovery and registration.
## Prerequisites
Please ensure that you have installed the Android SDK and NDK.
### NDK and SDK setup
External repository setup varies depending on whether you are using WORKSPACE
or bzlmod (MODULE.bazel). *Bzlmod is the preferred solution for Bazel 7+.*
Note that the MODULE.bazel and WORKSPACE setup stanzas are independent of
each other.
If you are using one dependency management solution, you don't need to add
the boilerplate for the other.
#### Bzlmod MODULE.bazel setup
Add the following snippet to your MODULE.bazel:
```python theme={null}
# NDK
bazel_dep(name = "rules_android_ndk", version = "0.1.3")
android_ndk_repository_extension = use_extension("@rules_android_ndk//:extension.bzl", "android_ndk_repository_extension")
use_repo(android_ndk_repository_extension, "androidndk")
register_toolchains("@androidndk//:all")
# SDK
bazel_dep(name = "rules_android", version = "0.6.6")
register_toolchains(
"@rules_android//toolchains/android:android_default_toolchain",
"@rules_android//toolchains/android_sdk:android_sdk_tools",
)
android_sdk_repository_extension = use_extension("@rules_android//rules/android_sdk_repository:rule.bzl", "android_sdk_repository_extension")
use_repo(android_sdk_repository_extension, "androidsdk")
register_toolchains("@androidsdk//:sdk-toolchain", "@androidsdk//:all")
```
#### Legacy WORKSPACE setup
Add the following snippet to your `WORKSPACE`:
```python theme={null}
load("@rules_android//rules:rules.bzl", "android_sdk_repository")
android_sdk_repository(
name = "androidsdk", # Required. Name *must* be "androidsdk".
path = "/path/to/sdk", # Optional. Can be omitted if `ANDROID_HOME` environment variable is set.
)
load("@rules_android_ndk//:rules.bzl", "android_ndk_repository")
android_ndk_repository(
name = "androidndk", # Required. Name *must* be "androidndk".
path = "/path/to/ndk", # Optional. Can be omitted if `ANDROID_NDK_HOME` environment variable is set.
)
```
Compatibility notes for WORKSPACE:
* Both `rules_android` and `rules_android_ndk` rules require extra
boilerplate not depicted in the WORKSPACE snippet above. For an up-to-date
and fully-formed instantiation stanza, see the [WORKSPACE](https://github.com/bazelbuild/rules_android_ndk/blob/main/examples/basic/WORKSPACE)
file of `rules_android_ndk`'s basic example app.
For more information about the `android_ndk_repository` rule, see its
[docstring](https://github.com/bazelbuild/rules_android_ndk/blob/7b4300f6d731139ca097f3332a5aebae5b0d91d0/rules.bzl#L18-L25).
## Quick start
To build C++ for Android, simply add `cc_library` dependencies to your
`android_binary` or `android_library` rules.
For example, given the following `BUILD` file for an Android app:
```python theme={null}
# In /app/src/main/BUILD.bazel
load("@rules_cc//cc:cc_library.bzl", "cc_library")
load("@rules_android//rules:rules.bzl", "android_binary", "android_library")
cc_library(
name = "jni_lib",
srcs = ["cpp/native-lib.cpp"],
)
android_library(
name = "lib",
srcs = ["java/com/example/android/bazel/MainActivity.java"],
resource_files = glob(["res/**/*"]),
custom_package = "com.example.android.bazel",
manifest = "LibraryManifest.xml",
deps = [":jni_lib"],
)
android_binary(
name = "app",
deps = [":lib"],
manifest = "AndroidManifest.xml",
)
```
This `BUILD` file results in the following target graph:
**Figure 1.** Build graph of Android project with cc\_library dependencies.
To build the app, simply run:
```posix-terminal theme={null}
bazel build //app/src/main:app --android_platforms=
```
Note that if you don't specify `--android_platforms`, your build will fail with
errors about missing JNI headers.
The `bazel build` command compiles the Java files, Android resource files, and
`cc_library` rules, and packages everything into an APK:
```posix-terminal theme={null}
$ zipinfo -1 bazel-bin/app/src/main/app.apk
nativedeps
lib/armeabi-v7a/libapp.so
classes.dex
AndroidManifest.xml
...
res/...
...
META-INF/CERT.SF
META-INF/CERT.RSA
META-INF/MANIFEST.MF
```
Bazel compiles all of the cc\_libraries into a single shared object (`.so`) file,
targeted the architectures specified by `--android_platforms`.
See the section on [configuring the target ABI](#configuring-target-abi) for
more details.
## Example setup
This example is available in the [Bazel examples repository](https://github.com/bazelbuild/examples/tree/master/android/ndk).
In the `BUILD.bazel` file, three targets are defined with the `android_binary`,
`android_library`, and `cc_library` rules.
The `android_binary` top-level target builds the APK.
The `cc_library` target contains a single C++ source file with a JNI function
implementation:
```c++ theme={null}
#include
#include
extern "C"
JNIEXPORT jstring
JNICALL
Java_com_example_android_bazel_MainActivity_stringFromJNI(
JNIEnv *env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
```
The `android_library` target specifies the Java sources, resource files, and the
dependency on a `cc_library` target. For this example, `MainActivity.java` loads
the shared object file `libapp.so`, and defines the method signature for the JNI
function:
```java theme={null}
public class MainActivity extends AppCompatActivity {
static {
System.loadLibrary("app");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
}
public native String stringFromJNI();
}
```
Note: The name of the native library is derived from the name of the top
level `android_binary` target. In this example, it is `app`.
## Configuring the target ABI
To configure the target ABI, use the `--android_platforms` flag as follows:
```posix-terminal theme={null}
bazel build //:app --android_platforms=comma-separated list of platforms
```
Just like the `--platforms` flag, the values passed to `--android_platforms` are
the labels of [`platform`](https://bazel.build/reference/be/platforms-and-toolchains#platform)
targets, using standard constraint values to describe your device.
For example, for an Android device with a 64-bit ARM processor, you'd define
your platform like this:
```py theme={null}
platform(
name = "android_arm64",
constraint_values = [
"@platforms//os:android",
"@platforms//cpu:arm64",
],
)
```
Every Android `platform` should use the [`@platforms//os:android`](https://github.com/bazelbuild/platforms/blob/33a3b209f94856193266871b1545054afb90bb28/os/BUILD#L36)
OS constraint. To migrate the CPU constraint, check this chart:
| CPU Value | Platform |
| - | - |
| `armeabi-v7a` | `@platforms//cpu:armv7` |
| `arm64-v8a` | `@platforms//cpu:arm64` |
| `x86` | `@platforms//cpu:x86_32` |
| `x86_64` | `@platforms//cpu:x86_64` |
And, of course, for a multi-architecture APK, you pass multiple labels, for
example: `--android_platforms=//:arm64,//:x86_64` (assuming you defined those in
your top-level `BUILD.bazel` file).
Bazel is unable to select a default Android platform, so one must be defined and
specified with `--android_platforms`.
Depending on the NDK revision and Android API level, the following ABIs are
available:
| NDK revision | ABIs |
| - | - |
| 16 and lower | armeabi, armeabi-v7a, arm64-v8a, mips, mips64, x86, x86\_64 |
| 17 and above | armeabi-v7a, arm64-v8a, x86, x86\_64 |
See [the NDK docs](https://developer.android.com/ndk/guides/abis.html)
for more information on these ABIs.
Multi-ABI Fat APKs are not recommended for release builds since they increase
the size of the APK, but can be useful for development and QA builds.
## Selecting a C++ standard
Use the following flags to build according to a C++ standard:
| C++ Standard | Flag |
| - | - |
| C++98 | Default, no flag needed |
| C++11 | `--cxxopt=-std=c++11` |
| C++14 | `--cxxopt=-std=c++14` |
| C++17 | `--cxxopt=-std=c++17` |
For example:
```posix-terminal theme={null}
bazel build //:app --cxxopt=-std=c++11
```
Read more about passing compiler and linker flags with `--cxxopt`, `--copt`, and
`--linkopt` in the [User Manual](/docs/user-manual#cxxopt).
Compiler and linker flags can also be specified as attributes in `cc_library`
using `copts` and `linkopts`. For example:
```python theme={null}
cc_library(
name = "jni_lib",
srcs = ["cpp/native-lib.cpp"],
copts = ["-std=c++11"],
linkopts = ["-ldl"], # link against libdl
)
```
## Building a `cc_library` for Android without using `android_binary`
To build a standalone `cc_binary` or `cc_library` for Android without using an
`android_binary`, use the `--platforms` flag.
For example, assuming you have defined Android platforms in
`my/platforms/BUILD`:
```posix-terminal theme={null}
bazel build //my/cc/jni:target \
--platforms=//my/platforms:x86_64
```
This approach affects the entire build tree.
Note: All of the targets on the command line must be compatible with
building for Android when specifying these flags, which may make it difficult to
use [Bazel wild-cards](/run/build#specifying-build-targets) like
`/...` and `:all`.
These flags can be put into a `bazelrc` config (one for each ABI), in
`project/.bazelrc`:
```
common:android_x86 --platforms=//my/platforms:x86
common:android_armeabi-v7a --platforms=//my/platforms:armeabi-v7a
# In general
common:android_ --platforms=//my/platforms:
```
Then, to build a `cc_library` for `x86` for example, run:
```posix-terminal theme={null}
bazel build //my/cc/jni:target --config=android_x86
```
In general, use this method for low-level targets (like `cc_library`) or when
you know exactly what you're building; rely on the automatic configuration
transitions from `android_binary` for high-level targets where you're expecting
to build a lot of targets you don't control.
# Android and Bazel
Source: https://bazel.build/docs/bazel-and-android
This page contains resources that help you use Bazel with Android projects. It
links to a tutorial, build rules, and other information specific to building
Android projects with Bazel.
## Getting started
The following resources will help you work with Bazel on Android projects:
* [Tutorial: Building an Android app](/start/android-app). This
tutorial is a good place to start learning about Bazel commands and concepts,
and how to build Android apps with Bazel.
* [Codelab: Building Android Apps with Bazel](https://developer.android.com/codelabs/bazel-android-intro#0).
This codelab explains how to build Android apps with Bazel.
## Features
Bazel has Android rules for building and testing Android apps, integrating with
the SDK/NDK, and creating emulator images. There are also Bazel plugins for
Android Studio and IntelliJ.
* [Android rules](/reference/be/android). The Build Encyclopedia describes the rules
for building and testing Android apps with Bazel.
* [Integration with Android Studio](/install/ide). Bazel is compatible with
Android Studio using the [Android Studio with Bazel](https://ij.bazel.build/)
plugin.
* [`mobile-install` for Android](/docs/mobile-install). Bazel's `mobile-install`
feature provides automated build-and-deploy functionality for building and
testing Android apps directly on Android devices and emulators.
* [Android instrumentation testing](/docs/android-instrumentation-test) on
emulators and devices.
* [Android NDK integration](/docs/android-ndk). Bazel supports compiling to
native code through direct NDK integration and the C++ rules.
* [Android build performance](/docs/android-build-performance). This page
provides information on optimizing build performance for Android apps.
## Further reading
* Integrating with dependencies from Google Maven and Maven Central with [rules\_jvm\_external](https://github.com/bazelbuild/rules_jvm_external).
* Learn [How Android Builds Work in Bazel](https://blog.bazel.build/2018/02/14/how-android-builds-work-in-bazel.html).
* Shrink and optimize your app with [R8](https://github.com/bazelbuild/rules_android/tree/main/docs/r8-optimization.md).
# Apple Apps and Bazel
Source: https://bazel.build/docs/bazel-and-apple
This page contains resources that help you use Bazel to build macOS and iOS
projects. It links to a tutorial, build rules, and other information specific to
using Bazel to build and test for those platforms.
## Working with Bazel
The following resources will help you work with Bazel on macOS and iOS projects:
* [Tutorial: Building an iOS app](/start/ios-app)
* [Objective-C build rules](/reference/be/objective-c)
* [General Apple rules](https://github.com/bazelbuild/rules_apple)
* [Integration with Xcode](/install/ide)
## Migrating to Bazel
If you currently build your macOS and iOS projects with Xcode, follow the steps
in the migration guide to start building them with Bazel:
* [Migrating from Xcode to Bazel](/migrate/xcode)
## Apple apps and new rules
**Note**: Creating new rules is for advanced build and test scenarios.
You do not need it when getting started with Bazel.
The following modules, configuration fragments, and providers will help you
[extend Bazel's capabilities](/extending/concepts)
when building your macOS and iOS projects:
* Modules:
* [`apple_bitcode_mode`](/rules/lib/builtins/apple_bitcode_mode)
* [`apple_common`](/rules/lib/toplevel/apple_common)
* [`apple_platform`](/rules/lib/builtins/apple_platform)
* [`apple_platform_type`](/rules/lib/builtins/apple_platform_type)
* [`apple_toolchain`](/rules/lib/builtins/apple_toolchain)
* Configuration fragments:
* [`apple`](/rules/lib/fragments/apple)
* Providers:
* [`ObjcProvider`](/rules/lib/providers/ObjcProvider)
* [`XcodeVersionConfig`](/rules/lib/providers/XcodeVersionConfig)
## Xcode selection
If your build requires Xcode, Bazel will select an appropriate version based on
the `--xcode_config` and `--xcode_version` flags. The `--xcode_config` consumes
the set of available Xcode versions and sets a default version if
`--xcode_version` is not passed. This default is overridden by the
`--xcode_version` flag, as long as it is set to an Xcode version that is
represented in the `--xcode_config` target.
If you do not pass `--xcode_config`, Bazel will use the autogenerated
[`XcodeVersionConfig`](/rules/lib/providers/XcodeVersionConfig) that represents the
Xcode versions available on your host machine. The default version is
the newest available Xcode version. This is appropriate for local execution.
If you are performing remote builds, you should set `--xcode_config` to an
[`xcode_config`](/reference/be/objective-c#xcode_config)
target whose `versions` attribute is a list of remotely available
[`xcode_version`](/reference/be/objective-c#xcode_version)
targets, and whose `default` attribute is one of these
[`xcode_versions`](/reference/be/objective-c#xcode_version).
If you are using dynamic execution, you should set `--xcode_config` to an
[`xcode_config`](/reference/be/objective-c#xcode_config)
target whose `remote_versions` attribute is an
[`available_xcodes`](/reference/be/workspace#available_xcodes)
target containing the remotely available Xcode versions, and whose
`local_versions` attribute is an
[`available_xcodes`](/reference/be/workspace#available_xcodes)
target containing the locally available Xcode versions. For `local_versions`,
you probably want to use the autogenerated
`@local_config_xcode//:host_available_xcodes`. The default Xcode version is the
newest mutually available version, if there is one, otherwise the default of the
`local_versions` target. If you prefer to use the `local_versions` default
as the default, you can pass `--experimental_prefer_mutual_default=false`.
# C++ and Bazel
Source: https://bazel.build/docs/bazel-and-cpp
This page contains resources that help you use Bazel with C++ projects. It links
to a tutorial, build rules, and other information specific to building C++
projects with Bazel.
## Working with Bazel
The following resources will help you work with Bazel on C++ projects:
* [Tutorial: Building a C++ project](/start/cpp)
* [C++ common use cases](/tutorials/cpp-use-cases)
* [C/C++ rules](/reference/be/c-cpp)
* Essential Libraries
* [Abseil](https://abseil.io/docs/cpp/quickstart)
* [Boost](https://github.com/nelhage/rules_boost)
* [HTTPS Requests: CPR and libcurl](https://github.com/hedronvision/bazel-make-cc-https-easy)
* [C++ toolchain configuration](/docs/cc-toolchain-config-reference)
* [Tutorial: Configuring C++ toolchains](/tutorials/ccp-toolchain-config)
* [Integrating with C++ rules](/configure/integrate-cpp)
## Best practices
In addition to [general Bazel best practices](/configure/best-practices), below are
best practices specific to C++ projects.
### BUILD files
Follow the guidelines below when creating your BUILD files:
* Each `BUILD` file should contain one [`cc_library`](/reference/be/c-cpp#cc_library)
rule target per compilation unit in the directory.
* You should granularize your C++ libraries as much as
possible to maximize incrementality and parallelize the build.
* If there is a single source file in `srcs`, name the library the same as
that C++ file's name. This library should contain C++ file(s), any matching
header file(s), and the library's direct dependencies. For example:
```python theme={null}
cc_library(
name = "mylib",
srcs = ["mylib.cc"],
hdrs = ["mylib.h"],
deps = [":lower-level-lib"]
)
```
* Use one `cc_test` rule target per `cc_library` target in the file. Name the
target `[library-name]_test` and the source file `[library-name]_test.cc`.
For example, a test target for the `mylib` library target shown above would
look like this:
```python theme={null}
cc_test(
name = "mylib_test",
srcs = ["mylib_test.cc"],
deps = [":mylib"]
)
```
### Include paths
Follow these guidelines for include paths:
* Make all include paths relative to the workspace directory.
* Use quoted includes (`#include "foo/bar/baz.h"`) for non-system headers, not
angle-brackets (`#include <foo/bar/baz.h>`).
* Avoid using UNIX directory shortcuts, such as `.` (current directory) or `..`
(parent directory).
* For legacy or `third_party` code that requires includes pointing outside the
project repository, such as external repository includes requiring a prefix,
use the [`include_prefix`](/reference/be/c-cpp#cc_library.include_prefix) and
[`strip_include_prefix`](/reference/be/c-cpp#cc_library.strip_include_prefix)
arguments on the `cc_library` rule target.
### Toolchain features
The following optional [features](/docs/cc-toolchain-config-reference#features)
can improve the hygiene of a C++ project. They can be enabled using the
`--features` command-line flag or the `features` attribute of
[`repo`](/external/overview#repo.bazel),
[`package`](/reference/be/functions#package) or `cc_*` rules:
* The `parse_headers` feature makes it so that the C++ compiler is used to parse
(but not compile) all header files in the built targets and their dependencies
when using the
[`--process_headers_in_dependencies`](/reference/command-line-reference#flag--process_headers_in_dependencies)
flag. This can help catch issues in header-only libraries and ensure that
headers are self-contained and independent of the order in which they are
included.
* The `layering_check` feature enforces that targets only include headers
provided by their direct dependencies. The default toolchain supports this
feature on Linux with `clang` as the compiler.
# Java and Bazel
Source: https://bazel.build/docs/bazel-and-java
This page contains resources that help you use Bazel with Java projects. It
links to a tutorial, build rules, and other information specific to building
Java projects with Bazel.
## Working with Bazel
The following resources will help you work with Bazel on Java projects:
* [Tutorial: Building a Java Project](/start/java)
* [Java rules](/reference/be/java)
## Migrating to Bazel
If you currently build your Java projects with Maven, follow the steps in the
migration guide to start building your Maven projects with Bazel:
* [Migrating from Maven to Bazel](/migrate/maven)
## Java versions
There are two relevant versions of Java that are set with configuration flags:
* the version of the source files in the repository
* the version of the Java runtime that is used to execute the code and to test
it
### Configuring the version of the source code in your repository
Without an additional configuration, Bazel assumes all Java source files in the
repository are written in a single Java version. To specify the version of the
sources in the repository add `build --java_language_version={ver}` to
`.bazelrc` file, where `{ver}` is for example `11`. Bazel repository owners
should set this flag so that Bazel and its users can reference the source code's
Java version number. For more details, see
[Java language version flag](/docs/user-manual#java-language-version).
### Configuring the JVM used to execute and test the code
Bazel uses one JDK for compilation and another JVM to execute and test the code.
By default Bazel compiles the code using a JDK it downloads and it executes and
tests the code with the JVM installed on the local machine. Bazel searches for
the JVM using `JAVA_HOME` or path.
The resulting binaries are compatible with locally installed JVM in system
libraries, which means the resulting binaries depend on what is installed on the
machine.
To configure the JVM used for execution and testing use `--java_runtime_version`
flag. The default value is `local_jdk`.
### Hermetic testing and compilation
To create a hermetic compile, you can use command line flag
`--java_runtime_version=remotejdk_11`. The code is compiled for, executed, and
tested on the JVM downloaded from a remote repository. For more details, see
[Java runtime version flag](/docs/user-manual#java_runtime_version).
### Configuring compilation and execution of build tools in Java
There is a second pair of JDK and JVM used to build and execute tools, which are
used in the build process, but are not in the build results. That JDK and JVM
are controlled using `--tool_java_language_version` and
`--tool_java_runtime_version`. Default values are `11` and `remotejdk_11`,
respectively.
#### Compiling using locally installed JDK
Bazel by default compiles using remote JDK, because it is overriding JDK's
internals. The compilation toolchains using locally installed JDK are configured,
however not used.
To compile using locally installed JDK, that is use the compilation toolchains
for local JDK, use additional flag `--extra_toolchains=@local_jdk//:all`,
however, mind that this may not work on JDK of arbitrary vendors.
For more details, see
[configuring Java toolchains](#config-java-toolchains).
## Best practices
In addition to [general Bazel best practices](/configure/best-practices), below are
best practices specific to Java projects.
### Directory structure
Prefer Maven's standard directory layout (sources under `src/main/java`, tests
under `src/test/java`).
### BUILD files
Follow these guidelines when creating your `BUILD` files:
* Use one `BUILD` file per directory containing Java sources, because this
improves build performance.
* Every `BUILD` file should contain one `java_library` rule that looks like
this:
```python theme={null}
java_library(
name = "directory-name",
srcs = glob(["*.java"]),
deps = [...],
)
```
* The name of the library should be the name of the directory containing the
`BUILD` file. This makes the label of the library shorter, that is use
`"//package"` instead of `"//package:package"`.
* The sources should be a non-recursive [`glob`](/reference/be/functions#glob) of
all Java files in the directory.
* Tests should be in a matching directory under `src/test` and depend on this
library.
## Creating new rules for advanced Java builds
**Note**: Creating new rules is for advanced build and test scenarios. You do
not need it when getting started with Bazel.
The following modules, configuration fragments, and providers will help you
[extend Bazel's capabilities](/extending/concepts) when building your Java
projects:
* Main Java module: [`java_common`](/rules/lib/toplevel/java_common)
* Main Java provider: [`JavaInfo`](/rules/lib/providers/JavaInfo)
* Configuration fragment: [`java`](/rules/lib/fragments/java)
* Other modules:
* [`java_annotation_processing`](/rules/lib/builtins/java_annotation_processing)
* [`java_compilation_info`](/rules/lib/providers/java_compilation_info)
* [`java_output_jars`](/rules/lib/providers/java_output_jars)
* [`JavaRuntimeInfo`](/rules/lib/providers/JavaRuntimeInfo)
* [`JavaToolchainInfo`](/rules/lib/providers/JavaToolchainInfo)
## Configuring the Java toolchains
Bazel uses two types of Java toolchains:
* execution, used to execute and test Java binaries, controlled with the
`--java_runtime_version` flag
* compilation, used to compile Java sources, controlled with the
`--java_language_version` flag
### Configuring additional execution toolchains
Execution toolchain is the JVM, either local or from a repository, with some
additional information about its version, operating system, and CPU
architecture.
Java execution toolchains may added using the `local_java_repository` or
`remote_java_repository` repo rules in a module extension. Adding the rule makes
the JVM available using a flag. When multiple definitions for the same operating
system and CPU architecture are given, the first one is used.
Example configuration of local JVM in MODULE.bazel:
```python theme={null}
custom_jdk = use_extension("@rules_java//java:extensions.bzl", "java_repository")
custom_jdk.local(
name = "additionaljdk", # Can be used with --java_runtime_version=additionaljdk, --java_runtime_version=11 or --java_runtime_version=additionaljdk_11
version = "11", # Optional, if not set it is autodetected
java_home = "/usr/lib/jdk-15/", # Path to directory containing bin/java
)
use_repo(custom_jdk, "additionaljdk")
register_toolchains("@additionaljdk//:all")
```
Example configuration of remote JVM:
```python theme={null}
custom_jdk = use_extension("@rules_java//java:extensions.bzl", "java_repository")
custom_jdk.remote(
name = "openjdk_canary_linux_arm",
prefix = "openjdk_canary", # Can be used with --java_runtime_version=openjdk_canary_11
version = "11", # or --java_runtime_version=11
target_compatible_with = [ # Specifies constraints this JVM is compatible with
"@platforms//cpu:arm",
"@platforms//os:linux",
],
urls = ..., # Other parameters are from http_repository rule.
sha256 = ...,
strip_prefix = ...
)
use_repo(custom_jdk, "openjdk_canary_linux_arm", "openjdk_canary_linux_arm_toolchain_config_repo")
register_toolchains("@openjdk_canary_linux_arm_toolchain_config_repo//:all")
```
### Configuring additional compilation toolchains
Compilation toolchain is composed of JDK and multiple tools that Bazel uses
during the compilation and that provides additional features, such as: Error
Prone, strict Java dependencies, header compilation, Android desugaring,
coverage instrumentation, and genclass handling for IDEs.
JavaBuilder is a Bazel-bundled tool that executes compilation, and provides the
aforementioned features. Actual compilation is executed using the internal
compiler by the JDK. The JDK used for compilation is specified by `java_runtime`
attribute of the toolchain.
Bazel overrides some JDK internals. In case of JDK version > 9,
`java.compiler` and `jdk.compiler` modules are patched using JDK's flag
`--patch_module`. In case of JDK version 8, the Java compiler is patched using
`-Xbootclasspath` flag.
VanillaJavaBuilder is a second implementation of JavaBuilder,
which does not modify JDK's internal compiler and does not have any of the
additional features. VanillaJavaBuilder is not used by any of the built-in
toolchains.
In addition to JavaBuilder, Bazel uses several other tools during compilation.
The `ijar` tool processes `jar` files to remove everything except call
signatures. Resulting jars are called header jars. They are used to improve the
compilation incrementality by only recompiling downstream dependents when the
body of a function changes.
The `singlejar` tool packs together multiple `jar` files into a single one.
The `genclass` tool post-processes the output of a Java compilation, and produces
a `jar` containing only the class files for sources that were generated by
annotation processors.
The `JacocoRunner` tool runs Jacoco over instrumented files and outputs results in
LCOV format.
The `TestRunner` tool executes JUnit 4 tests in a controlled environment.
You can reconfigure the compilation by adding `default_java_toolchain` macro to
a `BUILD` file and registering it either by adding `register_toolchains` rule to
the `MODULE.bazel` file or by using
[`--extra_toolchains`](/docs/user-manual#extra-toolchains) flag.
The toolchain is only used when the `source_version` attribute matches the
value specified by `--java_language_version` flag.
Example toolchain configuration:
```python theme={null}
load(
"@rules_java//toolchains:default_java_toolchain.bzl",
"default_java_toolchain", "DEFAULT_TOOLCHAIN_CONFIGURATION", "BASE_JDK9_JVM_OPTS", "DEFAULT_JAVACOPTS"
)
default_java_toolchain(
name = "repository_default_toolchain",
configuration = DEFAULT_TOOLCHAIN_CONFIGURATION, # One of predefined configurations
# Other parameters are from java_toolchain rule:
java_runtime = "@rules_java//toolchains:remote_jdk11", # JDK to use for compilation and toolchain's tools execution
jvm_opts = BASE_JDK9_JVM_OPTS + ["--enable_preview"], # Additional JDK options
javacopts = DEFAULT_JAVACOPTS + ["--enable_preview"], # Additional javac options
source_version = "9",
)
```
which can be used using `--extra_toolchains=//:repository_default_toolchain_definition`
or by adding `register_toolchains("//:repository_default_toolchain_definition")`
to the workpace.
Predefined configurations:
* `DEFAULT_TOOLCHAIN_CONFIGURATION`: all features, supports JDK versions >= 9
* `VANILLA_TOOLCHAIN_CONFIGURATION`: no additional features, supports JDKs of
arbitrary vendors.
* `PREBUILT_TOOLCHAIN_CONFIGURATION`: same as default, but only use prebuilt
tools (`ijar`, `singlejar`)
* `NONPREBUILT_TOOLCHAIN_CONFIGURATION`: same as default, but all tools are
built from sources (this may be useful on operating system with different
libc)
#### Configuring JVM and Java compiler flags
You may configure JVM and javac flags either with flags or with
`default_java_toolchain` attributes.
The relevant flags are `--jvmopt`, `--host_jvmopt`, `--javacopt`, and
`--host_javacopt`.
The relevant `default_java_toolchain` attributes are `javacopts`, `jvm_opts`,
`javabuilder_jvm_opts`, and `turbine_jvm_opts`.
#### Package specific Java compiler flags configuration
You can configure different Java compiler flags for specific source
files using `package_configuration` attribute of `default_java_toolchain`.
Please refer to the example below.
```python theme={null}
load("@rules_java//toolchains:default_java_toolchain.bzl", "default_java_toolchain")
# This is a convenience macro that inherits values from Bazel's default java_toolchain
default_java_toolchain(
name = "toolchain",
package_configuration = [
":error_prone",
],
visibility = ["//visibility:public"],
)
# This associates a set of javac flags with a set of packages
java_package_configuration(
name = "error_prone",
javacopts = [
"-Xep:MissingOverride:ERROR",
],
packages = ["error_prone_packages"],
)
# This is a regular package_group, which is used to specify a set of packages to apply flags to
package_group(
name = "error_prone_packages",
packages = [
"//foo/...",
"-//foo/bar/...", # this is an exclusion
],
)
```
#### Multiple versions of Java source code in a single repository
Bazel only supports compiling a single version of Java sources in a build.
build. This means that when building a Java test or an application, all
dependencies are built against the same Java version.
However, separate builds may be executed using different flags.
To make the task of using different flags easier, sets of flags for a specific
version may be grouped with `.bazelrc` configs":
```python theme={null}
build:java8 --java_language_version=8
build:java8 --java_runtime_version=local_jdk_8
build:java11 --java_language_version=11
build:java11 --java_runtime_version=remotejdk_11
```
These configs can be used with the `--config` flag, for example
`bazel test --config=java11 //:java11_test`.
# JavaScript and Bazel
Source: https://bazel.build/docs/bazel-and-javascript
This page contains resources that help you use Bazel with JavaScript projects.
It links to build rules and other information specific to building JavaScript
with Bazel.
The following resources will help you work with Bazel on JavaScript projects:
* [NodeJS toolchain](https://github.com/bazelbuild/rules_nodejs)
* [rules\_js](https://github.com/aspect-build/rules_js) - Bazel rules for building JavaScript programs
* [rules\_esbuild](https://github.com/aspect-build/rules_esbuild) - Bazel rules for [esbuild](https://esbuild.github.io) JS bundler
* [rules\_terser](https://github.com/aspect-build/rules_terser) - Bazel rules for [Terser](https://terser.org) - a JavaScript minifier
* [rules\_swc](https://github.com/aspect-build/rules_swc) - Bazel rules for [swc](https://swc.rs)
* [rules\_ts](https://github.com/aspect-build/rules_ts) - Bazel rules for [TypeScript](http://typescriptlang.org)
* [rules\_webpack](https://github.com/aspect-build/rules_webpack) - Bazel rules for [Webpack](https://webpack.js.org)
* [rules\_rollup](https://github.com/aspect-build/rules_rollup) - Bazel rules for [Rollup](https://rollupjs.org) - a JavaScript bundler
* [rules\_jest](https://github.com/aspect-build/rules_jest) - Bazel rules to run tests using [Jest](https://jestjs.io)
* [rules\_jasmine](https://github.com/aspect-build/rules_jasmine) - Bazel rules to run tests using [Jasmine](https://jasmine.github.io/)
* [rules\_cypress](https://github.com/aspect-build/rules_cypress) - Bazel rules to run tests using [Cypress](https://cypress.io)
* [rules\_deno](https://github.com/aspect-build/rules_deno) - Bazel rules for [Deno](http://deno.land)
# C++ Toolchain Configuration
Source: https://bazel.build/docs/cc-toolchain-config-reference
## Overview
To invoke the compiler with the right options, Bazel needs some knowledge about
the compiler internals, such as include directories and important flags.
In other words, Bazel needs a simplified model of the compiler to understand its
workings.
Bazel needs to know the following:
* Whether the compiler supports thinLTO, modules, dynamic linking, or PIC
(position independent code).
* Paths to the required tools such as gcc, ld, ar, objcopy, and so on.
* The built-in system include directories. Bazel needs these to validate that
all headers that were included in the source file were properly declared in
the `BUILD` file.
* The default sysroot.
* Which flags to use for compilation, linking, archiving.
* Which flags to use for the supported compilation modes (opt, dbg, fastbuild).
* Make variables specifically required by the compiler.
If the compiler has support for multiple architectures, Bazel needs to configure
them separately.
[`CcToolchainConfigInfo`](/rules/lib/providers/CcToolchainConfigInfo) is a provider that provides the necessary level of
granularity for configuring the behavior of Bazel's C++ rules. By default,
Bazel automatically configures `CcToolchainConfigInfo` for your build, but you
have the option to configure it manually. For that, you need a Starlark rule
that provides the `CcToolchainConfigInfo` and you need to point the
[`toolchain_config`](/reference/be/c-cpp#cc_toolchain.toolchain_config) attribute of the
[`cc_toolchain`](/reference/be/c-cpp#cc_toolchain) to your rule.
You can create the `CcToolchainConfigInfo` by calling
[`cc_common.create_cc_toolchain_config_info()`](/rules/lib/toplevel/cc_common#create_cc_toolchain_config_info).
You can find Starlark constructors for all structs you'll need in the process in
[`@rules_cc//cc:cc_toolchain_config_lib.bzl`](https://github.com/bazelbuild/rules_cc/blob/master/cc/cc_toolchain_config_lib.bzl).
When a C++ target enters the analysis phase, Bazel selects the appropriate
`cc_toolchain` target based on the `BUILD` file, and obtains the
`CcToolchainConfigInfo` provider from the target specified in the
`cc_toolchain.toolchain_config` attribute. The `cc_toolchain` target
passes this information to the C++ target through a `CcToolchainProvider`.
For example, a compile or link action, instantiated by a rule such as
`cc_binary` or `cc_library`, needs the following information:
* The compiler or linker to use
* Command-line flags for the compiler/linker
* Configuration flags passed through the `--copt/--linkopt` options
* Environment variables
* Artifacts needed in the sandbox in which the action executes
All of the above information except the artifacts required in the sandbox is
specified in the Starlark target that the `cc_toolchain` points to.
The artifacts to be shipped to the sandbox are declared in the `cc_toolchain`
target. For example, with the `cc_toolchain.linker_files` attribute you can
specify the linker binary and toolchain libraries to ship into the sandbox.
## Toolchain selection
The toolchain selection logic operates as follows:
1. User specifies a `cc_toolchain_suite` target in the `BUILD` file and points
Bazel to the target using the
[`--crosstool_top` option](/docs/user-manual#flag--crosstool_top).
2. The `cc_toolchain_suite` target references multiple toolchains. The
values of the `--cpu` and `--compiler` flags determine which of those
toolchains is selected, either based only on the `--cpu` flag value, or
based on a joint `--cpu | --compiler` value. The selection process is as
follows:
* If the `--compiler` option is specified, Bazel selects the
corresponding entry from the `cc_toolchain_suite.toolchains`
attribute with `--cpu | --compiler`. If Bazel does not find
a corresponding entry, it throws an error.
* If the `--compiler` option is not specified, Bazel selects
the corresponding entry from the `cc_toolchain_suite.toolchains`
attribute with just `--cpu`.
* If no flags are specified, Bazel inspects the host system and selects a
`--cpu` value based on its findings. See the
[inspection mechanism code](https://source.bazel.build/bazel/+/1b73bc37e184e71651eb631223dcce321ba16211:src/main/java/com/google/devtools/build/lib/analysis/config/AutoCpuConverter.java).
Once a toolchain has been selected, corresponding `feature` and `action_config`
objects in the Starlark rule govern the configuration of the build (that is,
items described later). These messages allow the implementation of
fully fledged C++ features in Bazel without modifying the
Bazel binary. C++ rules support multiple unique actions documented in detail
[in the Bazel source code](https://source.bazel.build/bazel/+/4f547a7ea86df80e4c76145ffdbb0c8b75ba3afa:tools/build_defs/cc/action_names.bzl).
## Features
A feature is an entity that requires command-line flags, actions,
constraints on the execution environment, or dependency alterations. A feature
can be something as simple as allowing `BUILD` files to select configurations of
flags, such as `treat_warnings_as_errors`, or interact with the C++ rules and
include new compile actions and inputs to the compilation, such as
`header_modules` or `thin_lto`.
Ideally, `CcToolchainConfigInfo` contains a list of features, where each
feature consists of one or more flag groups, each defining a list of flags
that apply to specific Bazel actions.
A feature is specified by name, which allows full decoupling of the Starlark
rule configuration from Bazel releases. In other words, a Bazel release does not
affect the behavior of `CcToolchainConfigInfo` configurations as long as those
configurations do not require the use of new features.
A feature is enabled in one of the following ways:
* The feature's `enabled` field is set to `true`.
* Bazel or the rule owner explicitly enable it.
* The user enables it through the `--feature` Bazel option or `features` rule
attribute.
Features can have interdependencies, depend on command line flags, `BUILD` file
settings, and other variables.
### Feature relationships
Dependencies are typically managed directly with Bazel, which simply enforces
the requirements and manages conflicts intrinsic to the nature of the features
defined in the build. The toolchain specification allows for more granular
constraints for use directly within the Starlark rule that govern feature
support and expansion. These are:
Feature-level. The feature is supported only if the specified required
features are enabled. For example, when a feature is only supported in
certain build modes (opt, dbg, or
fastbuild). If `requires` contains multiple `feature_set`s
the feature is supported if any of the `feature_set`s is satisfied
(when all specified features are enabled).
implies = \['feature']
Feature-level. This feature implies the specified feature(s).
Enabling a feature also implicitly enables all features implied by it
(that is, it functions recursively).
Also provides the ability to factor common subsets of functionality out of
a set of features, such as the common parts of sanitizers. Implied
features cannot be disabled.
provides = \['feature']
Feature-level. Indicates that this feature is one of several mutually
exclusive alternate features. For example, all of the sanitizers could
specify provides = \["sanitizer"].
This improves error handling by listing the alternatives if the user asks
for two or more mutually exclusive features at once.
Flag set-level. A feature can specify multiple flag sets with multiple.
When with\_features is specified, the flag set will only expand
to the build command if there is at least one with\_feature\_set
for which all of the features in the specified features set
are enabled, and all the features specified in not\_features
set are disabled.
If with\_features is not specified, the flag set will be
applied unconditionally for every action specified.
## Actions
Actions provide the flexibility to modify the circumstances under
which an action executes without assuming how the action will be run. An
`action_config` specifies the tool binary that an action invokes, while a
`feature` specifies the configuration (flags) that determine how that tool
behaves when the action is invoked.
[Features](#features) reference actions to signal which Bazel actions
they affect since actions can modify the Bazel action graph. The
`CcToolchainConfigInfo` provider contains actions that have flags and tools
associated with them, such as `c++-compile`. Flags are assigned to each action
by associating them with a feature.
Each action name represents a single type of action performed by Bazel, such as
compiling or linking. There is, however, a many-to-one relationship between
actions and Bazel action types, where a Bazel action type refers to a Java class
that implements an action (such as `CppCompileAction`). In particular, the
"assembler actions" and "compiler actions" in the table below are
`CppCompileAction`, while the link actions are `CppLinkAction`.
### Assembler actions
Action
Description
preprocess-assemble
Assemble with preprocessing. Typically for .S files.
assemble
Assemble without preprocessing. Typically for .s files.
### Compiler actions
Action
Description
cc-flags-make-variable
Propagates CC\_FLAGS to genrules.
c-compile
Compile as C.
c++-compile
Compile as C++.
c++-header-parsing
Run the compiler's parser on a header file to ensure that the header is
self-contained, as it will otherwise produce compilation errors. Applies
only to toolchains that support modules.
### Link actions
Action
Description
c++-link-dynamic-library
Link a shared library containing all of its dependencies.
c++-link-nodeps-dynamic-library
Link a shared library only containing cc\_library sources.
c++-link-executable
Link a final ready-to-run library.
### AR actions
AR actions assemble object files into archive libraries (`.a` files) via `ar`
and encode some semantics into the name.
Action
Description
c++-link-static-library
Create a static library (archive).
### LTO actions
Action
Description
lto-backend
ThinLTO action compiling bitcodes into native objects.
lto-index
ThinLTO action generating global index.
## Using action\_config
The `action_config` is a Starlark struct that describes a Bazel
action by specifying the tool (binary) to invoke during the action and sets of
flags, defined by features. These flags apply constraints to the action's
execution.
The `action_config()` constructor has the following parameters:
Attribute
Description
action\_name
The Bazel action to which this action corresponds.
Bazel uses this attribute to discover per-action tool and execution
requirements.
tools
The executable to invoke. The tool applied to the action will be the
first tool in the list with a feature set that matches the feature
configuration. Default value must be provided.
flag\_sets
A list of flags that applies to a group of actions. Same as for a
feature.
env\_sets
A list of environment constraints that applies to a group of actions.
Same as for a feature.
An `action_config` can require and imply other features and
action\_configs as dictated by the
[feature relationships](#feature-relationships) described earlier. This behavior
is similar to that of a feature.
The last two attributes are redundant against the corresponding attributes on
features and are included because some Bazel actions require certain flags or
environment variables and the goal is to avoid unnecessary `action_config`+`feature`
pairs. Typically, sharing a single feature across multiple `action_config`s is
preferred.
You can not define more than one `action_config` with the same `action_name`
within the same toolchain. This prevents ambiguity in tool paths
and enforces the intention behind `action_config` - that an action's properties
are clearly described in a single place in the toolchain.
### Using tool constructor
An`action_config` can specify a set of tools via its `tools` parameter.
The `tool()` constructor takes in the following parameters:
Field
Description
path
Path to the tool in question (relative to the current location).
with\_features
A list of feature sets out of which at least one must be satisfied
for this tool to apply.
For a given `action_config`, only a single `tool` applies
its tool path and execution requirements to the Bazel action. A tool is selected
by iterating through the `tools` attribute on an `action_config` until a tool
with a `with_feature` set matching the feature configuration is found
(see [Feature relationships](#feature-relationships) earlier on this page
for more information). You should end your tool lists with a default
tool that corresponds to an empty feature configuration.
### Example usage
Features and actions can be used together to implement Bazel actions
with diverse cross-platform semantics. For example, debug symbol generation on
macOS requires generating symbols in the compile action, then invoking a
specialized tool during the link action to create compressed dsym archive, and
then decompressing that archive to produce the application bundle and `.plist`
files consumable by Xcode.
With Bazel, this process can instead be implemented as follows, with
`unbundle-debuginfo` being a Bazel action:
load("@rules\_cc//cc:defs.bzl", "ACTION\_NAMES")
action\_configs = \[
action\_config (
action\_name = ACTION\_NAMES.cpp\_link\_executable,
tools = \[
tool(
with\_features = \[
with\_feature(features=\["generate-debug-symbols"]),
],
path = "toolchain/mac/ld-with-dsym-packaging",
),
tool (path = "toolchain/mac/ld"),
],
),
]
features = \[
feature(
name = "generate-debug-symbols",
flag\_sets = \[
flag\_set (
actions = \[
ACTION\_NAMES.c\_compile,
ACTION\_NAMES.cpp\_compile
],
flag\_groups = \[
flag\_group(
flags = \["-g"],
),
],
)
],
implies = \["unbundle-debuginfo"],
),
]
This same feature can be implemented entirely differently for Linux, which uses
`fission`, or for Windows, which produces `.pdb` files. For example, the
implementation for `fission`-based debug symbol generation might look as
follows:
load("@rules\_cc//cc:defs.bzl", "ACTION\_NAMES")
action\_configs = \[
action\_config (
name = ACTION\_NAMES.cpp\_compile,
tools = \[
tool(
path = "toolchain/bin/gcc",
),
],
),
]
features = \[
feature (
name = "generate-debug-symbols",
requires = \[with\_feature\_set(features = \["dbg"])],
flag\_sets = \[
flag\_set(
actions = \[ACTION\_NAMES.cpp\_compile],
flag\_groups = \[
flag\_group(
flags = \["-gsplit-dwarf"],
),
],
),
flag\_set(
actions = \[ACTION\_NAMES.cpp\_link\_executable],
flag\_groups = \[
flag\_group(
flags = \["-Wl", "--gdb-index"],
),
],
),
],
),
]
### Flag groups
`CcToolchainConfigInfo` allows you to bundle flags into groups that serve a
specific purpose. You can specify a flag within using pre-defined variables
within the flag value, which the compiler expands when adding the flag to the
build command. For example:
flag\_group (
flags = \["%"],
)
In this case, the contents of the flag will be replaced by the output file path
of the action.
Flag groups are expanded to the build command in the order in which they appear
in the list, top-to-bottom, left-to-right.
For flags that need to repeat with different values when added to the build
command, the flag group can iterate variables of type `list`. For example, the
variable `include_path` of type `list`:
flag\_group (
iterate\_over = "include\_paths",
flags = \["-I%"],
)
expands to `-I` for each path element in the `include_paths` list. All
flags (or `flag_group`s) in the body of a flag group declaration are expanded as
a unit. For example:
flag\_group (
iterate\_over = "include\_paths",
flags = \["-I", "%"],
)
expands to `-I ` for each path element in the `include_paths` list.
A variable can repeat multiple times. For example:
flag\_group (
iterate\_over = "include\_paths",
flags = \["-iprefix=%", "-isystem=%"],
)
expands to:
```
-iprefix= -isystem= -iprefix= -isystem=
```
Variables can correspond to structures accessible using dot-notation. For
example:
flag\_group (
flags = \["-l%"],
)
Structures can be nested and may also contain sequences. To prevent name clashes
and to be explicit, you must specify the full path through the fields. For
example:
flag\_group (
iterate\_over = "libraries\_to\_link",
flag\_groups = \[
flag\_group (
iterate\_over = "libraries\_to\_link.shared\_libraries",
flags = \["-l%"],
),
],
)
### Conditional expansion
Flag groups support conditional expansion based on the presence of a particular
variable or its field using the `expand_if_available`, `expand_if_not_available`,
`expand_if_true`, `expand_if_false`, or `expand_if_equal` attributes. For example:
flag\_group (
iterate\_over = "libraries\_to\_link",
flag\_groups = \[
flag\_group (
iterate\_over = "libraries\_to\_link.shared\_libraries",
flag\_groups = \[
flag\_group (
expand\_if\_available = "libraries\_to\_link.shared\_libraries.is\_whole\_archive",
flags = \["--whole\_archive"],
),
flag\_group (
flags = \["-l%"],
),
flag\_group (
expand\_if\_available = "libraries\_to\_link.shared\_libraries.is\_whole\_archive",
flags = \["--no\_whole\_archive"],
),
],
),
],
)
Note: The `--whole_archive` and `--no_whole_archive` options are added to
the build command only when a currently iterated library has an
`is_whole_archive` field.
## CcToolchainConfigInfo reference
This section provides a reference of build variables, features, and other
information required to successfully configure C++ rules.
### CcToolchainConfigInfo build variables
The following is a reference of `CcToolchainConfigInfo` build variables.
Note: The **Action** column indicates the relevant action type, if applicable.
Variable
Action
Description
source\_file
compile
Source file to compile.
input\_file
strip
Artifact to strip.
output\_file
compile, strip
Compilation output.
output\_assembly\_file
compile
Emitted assembly file. Applies only when the
compile action emits assembly text, typically when using the
--save\_temps flag. The contents are the same as for
output\_file.
output\_preprocess\_file
compile
Preprocessed output. Applies only to compile
actions that only preprocess the source files, typically when using the
--save\_temps flag. The contents are the same as for
output\_file.
includes
compile
Sequence of files the compiler must
unconditionally include in the compiled source.
include\_paths
compile
Sequence directories in which the compiler
searches for headers included using #include\
and #include "foo.h".
quote\_include\_paths
compile
Sequence of -iquote includes -
directories in which the compiler searches for headers included using
#include "foo.h".
system\_include\_paths
compile
Sequence of -isystem includes -
directories in which the compiler searches for headers included using
#include \.
dependency\_file
compile
The .d dependency file generated by the compiler.
preprocessor\_defines
compile
Sequence of defines, such as --DDEBUG.
pic
compile
Compiles the output as position-independent code.
gcov\_gcno\_file
compile
The gcov coverage file.
per\_object\_debug\_info\_file
compile
The per-object debug info (.dwp) file.
stripopts
strip
Sequence of stripopts.
legacy\_compile\_flags
compile
Sequence of flags from legacy
CROSSTOOL fields such as compiler\_flag,
optional\_compiler\_flag, cxx\_flag, and
optional\_cxx\_flag.
user\_compile\_flags
compile
Sequence of flags from either the
copt rule attribute or the --copt,
--cxxopt, and --conlyopt flags.
unfiltered\_compile\_flags
compile
Sequence of flags from the
unfiltered\_cxx\_flag legacy CROSSTOOL field or the
unfiltered\_compile\_flags feature. These are not filtered by
the nocopts rule attribute.
sysroot
The sysroot.
runtime\_library\_search\_directories
link
Entries in the linker runtime search path (usually
set with the -rpath flag).
library\_search\_directories
link
Entries in the linker search path (usually set with
the -L flag).
libraries\_to\_link
link
Flags providing files to link as inputs in the linker invocation.
def\_file\_path
link
Location of def file used on Windows with MSVC.
linker\_param\_file
link
Location of linker param file created by bazel to
overcome command line length limit.
output\_execpath
link
Execpath of the output of the linker.
generate\_interface\_library
link
"yes" or "no" depending on whether interface library should
be generated.
interface\_library\_builder\_path
link
Path to the interface library builder tool.
interface\_library\_input\_path
link
Input for the interface library ifso builder tool.
interface\_library\_output\_path
link
Path where to generate interface library using the ifso builder tool.
legacy\_link\_flags
link
Linker flags coming from the legacy CROSSTOOL fields.
user\_link\_flags
link
Linker flags coming from the --linkopt
or linkopts attribute.
linkstamp\_paths
link
A build variable giving linkstamp paths.
force\_pic
link
Presence of this variable indicates that PIC/PIE code should
be generated (Bazel option `--force_pic` was passed).
strip\_debug\_symbols
link
Presence of this variable indicates that the debug
symbols should be stripped.
is\_cc\_test
link
Truthy when current action is a cc\_test
linking action, false otherwise.
is\_using\_fission
compile, link
Presence of this variable indicates that fission (per-object debug info)
is activated. Debug info will be in .dwo files instead
of .o files and the compiler and linker need to know this.
fdo\_instrument\_path
compile, link
Path to the directory that stores FDO instrumentation profile.
fdo\_profile\_path
compile
Path to FDO profile.
fdo\_prefetch\_hints\_path
compile
Path to the cache prefetch profile.
cs\_fdo\_instrument\_path
compile, link
Path to the directory that stores context sensitive FDO
instrumentation profile.
### Well-known features
The following is a reference of features and their activation
conditions.
Feature
Documentation
opt | dbg | fastbuild
Enabled by default based on compilation mode.
static\_linking\_mode | dynamic\_linking\_mode
Enabled by default based on linking mode.
per\_object\_debug\_info
Enabled if the supports\_fission feature is specified and
enabled and the current compilation mode is specified in the
--fission flag.
supports\_start\_end\_lib
If enabled (and the option --start\_end\_lib is set), Bazel
will not link against static libraries but instead use the
--start-lib/--end-lib linker options to link against objects
directly. This speeds up the build since Bazel doesn't have to build
static libraries.
supports\_interface\_shared\_libraries
If enabled (and the option --interface\_shared\_objects is
set), Bazel will link targets that have linkstatic set to
False (cc\_tests by default) against interface shared
libraries. This makes incremental relinking faster.
supports\_dynamic\_linker
If enabled, C++ rules will know the toolchain can produce shared
libraries.
static\_link\_cpp\_runtimes
If enabled, Bazel will link the C++ runtime statically in static linking
mode and dynamically in dynamic linking mode. Artifacts
specified in the cc\_toolchain.static\_runtime\_lib or
cc\_toolchain.dynamic\_runtime\_lib attribute (depending on the
linking mode) will be added to the linking actions.
supports\_pic
If enabled, toolchain will know to use PIC objects for dynamic libraries.
The `pic` variable is present whenever PIC compilation is needed. If not enabled
by default, and `--force_pic` is passed, Bazel will request `supports_pic` and
validate that the feature is enabled. If the feature is missing, or couldn't
be enabled, `--force_pic` cannot be used.
static\_linking\_mode | dynamic\_linking\_mode
Enabled by default based on linking mode.
no\_legacy\_features
Prevents Bazel from adding legacy features to
the C++ configuration when present. See the complete list of
features below.
shorten\_virtual\_includes
If enabled, virtual include header files are linked under bin/\_virtual\_includes/\ instead of bin/\/\_virtual\_includes/\. Useful on Windows to avoid long path issue with MSVC.
#### Legacy features patching logic
Bazel applies the following changes to the toolchain's features for backwards
compatibility:
Moves legacy\_compile\_flags feature to the top of the toolchain
Moves default\_compile\_flags feature to the top of the toolchain
Adds dependency\_file (if not present) feature to the top of the toolchain
Adds pic (if not present) feature to the top of the toolchain
Adds per\_object\_debug\_info (if not present) feature to the top of the toolchain
Adds preprocessor\_defines (if not present) feature to the top of the toolchain
Adds includes (if not present) feature to the top of the toolchain
Adds include\_paths (if not present) feature to the top of the toolchain
Adds fdo\_instrument (if not present) feature to the top of the toolchain
Adds fdo\_optimize (if not present) feature to the top of the toolchain
Adds cs\_fdo\_instrument (if not present) feature to the top of the toolchain
Adds cs\_fdo\_optimize (if not present) feature to the top of the toolchain
Adds fdo\_prefetch\_hints (if not present) feature to the top of the toolchain
Adds autofdo (if not present) feature to the top of the toolchain
Adds build\_interface\_libraries (if not present) feature to the top of the toolchain
Adds dynamic\_library\_linker\_tool (if not present) feature to the top of the toolchain
Adds shared\_flag (if not present) feature to the top of the toolchain
Adds linkstamps (if not present) feature to the top of the toolchain
Adds output\_execpath\_flags (if not present) feature to the top of the toolchain
Adds runtime\_library\_search\_directories (if not present) feature to the top of the toolchain
Adds library\_search\_directories (if not present) feature to the top of the toolchain
Adds archiver\_flags (if not present) feature to the top of the toolchain
Adds libraries\_to\_link (if not present) feature to the top of the toolchain
Adds force\_pic\_flags (if not present) feature to the top of the toolchain
Adds user\_link\_flags (if not present) feature to the top of the toolchain
Adds legacy\_link\_flags (if not present) feature to the top of the toolchain
Adds static\_libgcc (if not present) feature to the top of the toolchain
Adds fission\_support (if not present) feature to the top of the toolchain
Adds strip\_debug\_symbols (if not present) feature to the top of the toolchain
Adds coverage (if not present) feature to the top of the toolchain
Adds llvm\_coverage\_map\_format (if not present) feature to the top of the toolchain
Adds gcc\_coverage\_map\_format (if not present) feature to the top of the toolchain
Adds fully\_static\_link (if not present) feature to the bottom of the toolchain
Adds user\_compile\_flags (if not present) feature to the bottom of the toolchain
Adds sysroot (if not present) feature to the bottom of the toolchain
Adds unfiltered\_compile\_flags (if not present) feature to the bottom of the toolchain
Adds linker\_param\_file (if not present) feature to the bottom of the toolchain
Adds compiler\_input\_flags (if not present) feature to the bottom of the toolchain
Adds compiler\_output\_flags (if not present) feature to the bottom of the toolchain
This is a long list of features. The plan is to get rid of them once
[Crosstool in Starlark](https://github.com/bazelbuild/bazel/issues/5380) is
done. For the curious reader see the implementation in
[CppActionConfigs](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/rules/cpp/CppActionConfigs.java?q=cppactionconfigs\&ss=bazel),
and for production toolchains consider adding `no_legacy_features` to make
the toolchain more standalone.
# Configurable Build Attributes
Source: https://bazel.build/docs/configurable-attributes
***Configurable attributes***, commonly known as [`select()`](/reference/be/functions#select), is a Bazel feature that lets users toggle the values
of build rule attributes at the command line.
This can be used, for example, for a multiplatform library that automatically
chooses the appropriate implementation for the architecture, or for a
feature-configurable binary that can be customized at build time.
## Example
```python theme={null}
# myapp/BUILD
cc_binary(
name = "mybinary",
srcs = ["main.cc"],
deps = select({
":arm_build": [":arm_lib"],
":x86_debug_build": [":x86_dev_lib"],
"//conditions:default": [":generic_lib"],
}),
)
config_setting(
name = "arm_build",
values = {"cpu": "arm"},
)
config_setting(
name = "x86_debug_build",
values = {
"cpu": "x86",
"compilation_mode": "dbg",
},
)
```
This declares a `cc_binary` that "chooses" its deps based on the flags at the
command line. Specifically, `deps` becomes:
Command
deps =
bazel build //myapp:mybinary --cpu=arm
\[":arm\_lib"]
bazel build //myapp:mybinary -c dbg --cpu=x86
\[":x86\_dev\_lib"]
bazel build //myapp:mybinary --cpu=ppc
\[":generic\_lib"]
bazel build //myapp:mybinary -c dbg --cpu=ppc
\[":generic\_lib"]
`select()` serves as a placeholder for a value that will be chosen based on
*configuration conditions*, which are labels referencing [`config_setting`](/reference/be/general#config_setting)
targets. By using `select()` in a configurable attribute, the attribute
effectively adopts different values when different conditions hold.
Matches must be unambiguous: if multiple conditions match then either:
* They all resolve to the same value. For example, when running on linux x86, this is unambiguous
`{"@platforms//os:linux": "Hello", "@platforms//cpu:x86_64": "Hello"}` because both branches resolve to "hello".
* One's `values` is a strict superset of all others'. For example, `values = {"cpu": "x86", "compilation_mode": "dbg"}`
is an unambiguous specialization of `values = {"cpu": "x86"}`.
The built-in condition [`//conditions:default`](#default-condition) automatically matches when
nothing else does.
While this example uses `deps`, `select()` works just as well on `srcs`,
`resources`, `cmd`, and most other attributes. Only a small number of attributes
are *non-configurable*, and these are clearly annotated. For example,
`config_setting`'s own
[`values`](/reference/be/general#config_setting.values) attribute is non-configurable.
## `select()` and dependencies
Certain attributes change the build parameters for all transitive dependencies
under a target. For example, `genrule`'s `tools` changes `--cpu` to the CPU of
the machine running Bazel (which, thanks to cross-compilation, may be different
than the CPU the target is built for). This is known as a
[configuration transition](/reference/glossary#transition).
Given
```python theme={null}
#myapp/BUILD
config_setting(
name = "arm_cpu",
values = {"cpu": "arm"},
)
config_setting(
name = "x86_cpu",
values = {"cpu": "x86"},
)
genrule(
name = "my_genrule",
srcs = select({
":arm_cpu": ["g_arm.src"],
":x86_cpu": ["g_x86.src"],
}),
tools = select({
":arm_cpu": [":tool1"],
":x86_cpu": [":tool2"],
}),
)
cc_binary(
name = "tool1",
srcs = select({
":arm_cpu": ["armtool.cc"],
":x86_cpu": ["x86tool.cc"],
}),
)
```
running
```sh theme={null}
$ bazel build //myapp:my_genrule --cpu=arm
```
on an `x86` developer machine binds the build to `g_arm.src`, `tool1`, and
`x86tool.cc`. Both of the `select`s attached to `my_genrule` use `my_genrule`'s
build parameters, which include `--cpu=arm`. The `tools` attribute changes
`--cpu` to `x86` for `tool1` and its transitive dependencies. The `select` on
`tool1` uses `tool1`'s build parameters, which include `--cpu=x86`.
## Configuration conditions
Each key in a configurable attribute is a label reference to a
[`config_setting`](/reference/be/general#config_setting) or
[`constraint_value`](/reference/be/platforms-and-toolchains#constraint_value).
`config_setting` is just a collection of
expected command line flag settings. By encapsulating these in a target, it's
easy to maintain "standard" conditions users can reference from multiple places.
`constraint_value` provides support for [multi-platform behavior](#platforms).
### Built-in flags
Flags like `--cpu` are built into Bazel: the build tool natively understands
them for all builds in all projects. These are specified with
[`config_setting`](/reference/be/general#config_setting)'s
[`values`](/reference/be/general#config_setting.values) attribute:
```python theme={null}
config_setting(
name = "meaningful_condition_name",
values = {
"flag1": "value1",
"flag2": "value2",
...
},
)
```
`flagN` is a flag name (without `--`, so `"cpu"` instead of `"--cpu"`). `valueN`
is the expected value for that flag. `:meaningful_condition_name` matches if
*every* entry in `values` matches. Order is irrelevant.
`valueN` is parsed as if it was set on the command line. This means:
* `values = { "compilation_mode": "opt" }` matches `bazel build -c opt`
* `values = { "force_pic": "true" }` matches `bazel build --force_pic=1`
* `values = { "force_pic": "0" }` matches `bazel build --noforce_pic`
`config_setting` only supports flags that affect target behavior. For example,
[`--show_progress`](/docs/user-manual#show-progress) isn't allowed because
it only affects how Bazel reports progress to the user. Targets can't use that
flag to construct their results. The exact set of supported flags isn't
documented. In practice, most flags that "make sense" work.
### Custom flags
You can model your own project-specific flags with
[Starlark build settings][BuildSettings]. Unlike built-in flags, these are
defined as build targets, so Bazel references them with target labels.
These are triggered with [`config_setting`](/reference/be/general#config_setting)'s
[`flag_values`](/reference/be/general#config_setting.flag_values)
attribute:
```python theme={null}
config_setting(
name = "meaningful_condition_name",
flag_values = {
"//myflags:flag1": "value1",
"//myflags:flag2": "value2",
...
},
)
```
Behavior is the same as for [built-in flags](#built-in-flags). See [here](https://github.com/bazelbuild/examples/tree/HEAD/configurations/select_on_build_setting)
for a working example.
[`--define`](/reference/command-line-reference#flag--define)
is an alternative legacy syntax for custom flags (for example
`--define foo=bar`). This can be expressed either in the
[values](/reference/be/general#config_setting.values) attribute
(`values = {"define": "foo=bar"}`) or the
[define\_values](/reference/be/general#config_setting.define_values) attribute
(`define_values = {"foo": "bar"}`). `--define` is only supported for backwards
compatibility. Prefer Starlark build settings whenever possible.
`values`, `flag_values`, and `define_values` evaluate independently. The
`config_setting` matches if all values across all of them match.
## The default condition
The built-in condition `//conditions:default` matches when no other condition
matches.
Because of the "exactly one match" rule, a configurable attribute with no match
and no default condition emits a `"no matching conditions"` error. This can
protect against silent failures from unexpected settings:
```python theme={null}
# myapp/BUILD
config_setting(
name = "x86_cpu",
values = {"cpu": "x86"},
)
cc_library(
name = "x86_only_lib",
srcs = select({
":x86_cpu": ["lib.cc"],
}),
)
```
```sh theme={null}
$ bazel build //myapp:x86_only_lib --cpu=arm
ERROR: Configurable attribute "srcs" doesn't match this configuration (would
a default condition help?).
Conditions checked:
//myapp:x86_cpu
```
For even clearer errors, you can set custom messages with `select()`'s
[`no_match_error`](#custom-error-messages) attribute.
## Platforms
While the ability to specify multiple flags on the command line provides
flexibility, it can also be burdensome to individually set each one every time
you want to build a target.
[Platforms](/extending/platforms)
let you consolidate these into simple bundles.
```python theme={null}
# myapp/BUILD
sh_binary(
name = "my_rocks",
srcs = select({
":basalt": ["pyroxene.sh"],
":marble": ["calcite.sh"],
"//conditions:default": ["feldspar.sh"],
}),
)
config_setting(
name = "basalt",
constraint_values = [
":black",
":igneous",
],
)
config_setting(
name = "marble",
constraint_values = [
":white",
":metamorphic",
],
)
# constraint_setting acts as an enum type, and constraint_value as an enum value.
constraint_setting(name = "color")
constraint_value(name = "black", constraint_setting = "color")
constraint_value(name = "white", constraint_setting = "color")
constraint_setting(name = "texture")
constraint_value(name = "smooth", constraint_setting = "texture")
constraint_setting(name = "type")
constraint_value(name = "igneous", constraint_setting = "type")
constraint_value(name = "metamorphic", constraint_setting = "type")
platform(
name = "basalt_platform",
constraint_values = [
":black",
":igneous",
],
)
platform(
name = "marble_platform",
constraint_values = [
":white",
":smooth",
":metamorphic",
],
)
```
The platform can be specified on the command line. It activates the
`config_setting`s that contain a subset of the platform's `constraint_values`,
allowing those `config_setting`s to match in `select()` expressions.
For example, in order to set the `srcs` attribute of `my_rocks` to `calcite.sh`,
you can simply run
```sh theme={null}
bazel build //my_app:my_rocks --platforms=//myapp:marble_platform
```
Without platforms, this might look something like
```sh theme={null}
bazel build //my_app:my_rocks --define color=white --define texture=smooth --define type=metamorphic
```
`select()` can also directly read `constraint_value`s:
```python theme={null}
constraint_setting(name = "type")
constraint_value(name = "igneous", constraint_setting = "type")
constraint_value(name = "metamorphic", constraint_setting = "type")
sh_binary(
name = "my_rocks",
srcs = select({
":igneous": ["igneous.sh"],
":metamorphic" ["metamorphic.sh"],
}),
)
```
This saves the need for boilerplate `config_setting`s when you only need to
check against single values.
Platforms are still under development. See the
[documentation](/concepts/platforms) for details.
## Combining `select()`s
`select` can appear multiple times in the same attribute:
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"] +
select({
":armeabi_mode": ["armeabi_src.sh"],
":x86_mode": ["x86_src.sh"],
}) +
select({
":opt_mode": ["opt_extras.sh"],
":dbg_mode": ["dbg_extras.sh"],
}),
)
```
Note: Some restrictions apply on what can be combined in the `select`s values:
* Duplicate labels can appear in different paths of the same `select`.
* Duplicate labels can *not* appear within the same path of a `select`.
* Duplicate labels can *not* appear across multiple combined `select`s (no matter what path)
`select` cannot appear inside another `select`. If you need to nest `selects`
and your attribute takes other targets as values, use an intermediate target:
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":armeabi_mode": [":armeabi_lib"],
...
}),
)
sh_library(
name = "armeabi_lib",
srcs = select({
":opt_mode": ["armeabi_with_opt.sh"],
...
}),
)
```
If you need a `select` to match when multiple conditions match, consider [AND chaining](#and-chaining).
## OR chaining
Consider the following:
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1": [":standard_lib"],
":config2": [":standard_lib"],
":config3": [":standard_lib"],
":config4": [":special_lib"],
}),
)
```
Most conditions evaluate to the same dep. But this syntax is hard to read and
maintain. It would be nice to not have to repeat `[":standard_lib"]` multiple
times.
One option is to predefine the value as a BUILD variable:
```python theme={null}
STANDARD_DEP = [":standard_lib"]
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1": STANDARD_DEP,
":config2": STANDARD_DEP,
":config3": STANDARD_DEP,
":config4": [":special_lib"],
}),
)
```
This makes it easier to manage the dependency. But it still causes unnecessary
duplication.
For more direct support, use one of the following:
### `selects.with_or`
The
[with\_or](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectswith_or)
macro in [Skylib](https://github.com/bazelbuild/bazel-skylib)'s
[`selects`](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md)
module supports `OR`ing conditions directly inside a `select`:
```python theme={null}
load("@bazel_skylib//lib:selects.bzl", "selects")
```
```python theme={null}
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = selects.with_or({
(":config1", ":config2", ":config3"): [":standard_lib"],
":config4": [":special_lib"],
}),
)
```
### `selects.config_setting_group`
The
[config\_setting\_group](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectsconfig_setting_group)
macro in [Skylib](https://github.com/bazelbuild/bazel-skylib)'s
[`selects`](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md)
module supports `OR`ing multiple `config_setting`s:
```python theme={null}
load("@bazel_skylib//lib:selects.bzl", "selects")
```
```python theme={null}
config_setting(
name = "config1",
values = {"cpu": "arm"},
)
config_setting(
name = "config2",
values = {"compilation_mode": "dbg"},
)
selects.config_setting_group(
name = "config1_or_2",
match_any = [":config1", ":config2"],
)
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1_or_2": [":standard_lib"],
"//conditions:default": [":other_lib"],
}),
)
```
Unlike `selects.with_or`, different targets can share `:config1_or_2` across
different attributes.
It's an error for multiple conditions to match unless one is an unambiguous
"specialization" of the others or they all resolve to the same value. See [here](#configurable-build-example) for details.
## AND chaining
If you need a `select` branch to match when multiple conditions match, use the
[Skylib](https://github.com/bazelbuild/bazel-skylib) macro
[config\_setting\_group](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectsconfig_setting_group):
```python theme={null}
config_setting(
name = "config1",
values = {"cpu": "arm"},
)
config_setting(
name = "config2",
values = {"compilation_mode": "dbg"},
)
selects.config_setting_group(
name = "config1_and_2",
match_all = [":config1", ":config2"],
)
sh_binary(
name = "my_target",
srcs = ["always_include.sh"],
deps = select({
":config1_and_2": [":standard_lib"],
"//conditions:default": [":other_lib"],
}),
)
```
Unlike OR chaining, existing `config_setting`s can't be directly `AND`ed
inside a `select`. You have to explicitly wrap them in a `config_setting_group`.
## Custom error messages
By default, when no condition matches, the target the `select()` is attached to
fails with the error:
```sh theme={null}
ERROR: Configurable attribute "deps" doesn't match this configuration (would
a default condition help?).
Conditions checked:
//tools/cc_target_os:darwin
//tools/cc_target_os:android
```
This can be customized with the [`no_match_error`](/reference/be/functions#select)
attribute:
```python theme={null}
cc_library(
name = "my_lib",
deps = select(
{
"//tools/cc_target_os:android": [":android_deps"],
"//tools/cc_target_os:windows": [":windows_deps"],
},
no_match_error = "Please build with an Android or Windows toolchain",
),
)
```
```sh theme={null}
$ bazel build //myapp:my_lib
ERROR: Configurable attribute "deps" doesn't match this configuration: Please
build with an Android or Windows toolchain
```
## Rules compatibility
Rule implementations receive the *resolved values* of configurable
attributes. For example, given:
```python theme={null}
# myapp/BUILD
some_rule(
name = "my_target",
some_attr = select({
":foo_mode": [":foo"],
":bar_mode": [":bar"],
}),
)
```
```sh theme={null}
$ bazel build //myapp/my_target --define mode=foo
```
Rule implementation code sees `ctx.attr.some_attr` as `[":foo"]`.
Macros can accept `select()` clauses and pass them through to native
rules. But *they cannot directly manipulate them*. For example, there's no way
for a macro to convert
```python theme={null}
select({"foo": "val"}, ...)
```
to
```python theme={null}
select({"foo": "val_with_suffix"}, ...)
```
This is for two reasons.
First, macros that need to know which path a `select` will choose *cannot work*
because macros are evaluated in Bazel's [loading phase](/run/build#loading),
which occurs before flag values are known.
This is a core Bazel design restriction that's unlikely to change any time soon.
Second, macros that just need to iterate over *all* `select` paths, while
technically feasible, lack a coherent UI. Further design is necessary to change
this.
## Bazel query and cquery
Bazel [`query`](/query/guide) operates over Bazel's
[loading phase](/reference/glossary#loading-phase).
This means it doesn't know what command line flags a target uses since those
flags aren't evaluated until later in the build (in the
[analysis phase](/reference/glossary#analysis-phase)).
So it can't determine which `select()` branches are chosen.
Bazel [`cquery`](/query/cquery) operates after Bazel's analysis phase, so it has
all this information and can accurately resolve `select()`s.
Consider:
```python theme={null}
load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
```
```python theme={null}
# myapp/BUILD
string_flag(
name = "dog_type",
build_setting_default = "cat"
)
cc_library(
name = "my_lib",
deps = select({
":long": [":foo_dep"],
":short": [":bar_dep"],
}),
)
config_setting(
name = "long",
flag_values = {":dog_type": "dachshund"},
)
config_setting(
name = "short",
flag_values = {":dog_type": "pug"},
)
```
`query` overapproximates `:my_lib`'s dependencies:
```sh theme={null}
$ bazel query 'deps(//myapp:my_lib)'
//myapp:my_lib
//myapp:foo_dep
//myapp:bar_dep
```
while `cquery` shows its exact dependencies:
```sh theme={null}
$ bazel cquery 'deps(//myapp:my_lib)' --//myapp:dog_type=pug
//myapp:my_lib
//myapp:bar_dep
```
## FAQ
### Why doesn't select() work in macros?
select() *does* work in rules! See [Rules compatibility](#rules-compatibility) for
details.
The key issue this question usually means is that select() doesn't work in
*macros*. These are different than *rules*. See the
documentation on [rules](/extending/rules) and [macros](/extending/macros)
to understand the difference.
Here's an end-to-end example:
Define a rule and macro:
```python theme={null}
# myapp/defs.bzl
# Rule implementation: when an attribute is read, all select()s have already
# been resolved. So it looks like a plain old attribute just like any other.
def _impl(ctx):
name = ctx.attr.name
allcaps = ctx.attr.my_config_string.upper() # This works fine on all values.
print("My name is " + name + " with custom message: " + allcaps)
# Rule declaration:
my_custom_bazel_rule = rule(
implementation = _impl,
attrs = {"my_config_string": attr.string()},
)
# Macro declaration:
def my_custom_bazel_macro(name, my_config_string):
allcaps = my_config_string.upper() # This line won't work with select(s).
print("My name is " + name + " with custom message: " + allcaps)
```
Instantiate the rule and macro:
```python theme={null}
# myapp/BUILD
load("//myapp:defs.bzl", "my_custom_bazel_rule")
load("//myapp:defs.bzl", "my_custom_bazel_macro")
my_custom_bazel_rule(
name = "happy_rule",
my_config_string = select({
"//third_party/bazel_platforms/cpu:x86_32": "first string",
"//third_party/bazel_platforms/cpu:ppc": "second string",
}),
)
my_custom_bazel_macro(
name = "happy_macro",
my_config_string = "fixed string",
)
my_custom_bazel_macro(
name = "sad_macro",
my_config_string = select({
"//third_party/bazel_platforms/cpu:x86_32": "first string",
"//third_party/bazel_platforms/cpu:ppc": "other string",
}),
)
```
Building fails because `sad_macro` can't process the `select()`:
```sh theme={null}
$ bazel build //myapp:all
ERROR: /myworkspace/myapp/BUILD:17:1: Traceback
(most recent call last):
File "/myworkspace/myapp/BUILD", line 17
my_custom_bazel_macro(name = "sad_macro", my_config_stri..."}))
File "/myworkspace/myapp/defs.bzl", line 4, in
my_custom_bazel_macro
my_config_string.upper()
type 'select' has no method upper().
ERROR: error loading package 'myapp': Package 'myapp' contains errors.
```
Building succeeds when you comment out `sad_macro`:
```sh theme={null}
# Comment out sad_macro so it doesn't mess up the build.
$ bazel build //myapp:all
DEBUG: /myworkspace/myapp/defs.bzl:5:3: My name is happy_macro with custom message: FIXED STRING.
DEBUG: /myworkspace/myapp/hi.bzl:15:3: My name is happy_rule with custom message: FIRST STRING.
```
This is impossible to change because *by definition* macros are evaluated before
Bazel reads the build's command line flags. That means there isn't enough
information to evaluate select()s.
Macros can, however, pass `select()`s as opaque blobs to rules:
```python theme={null}
# myapp/defs.bzl
def my_custom_bazel_macro(name, my_config_string):
print("Invoking macro " + name)
my_custom_bazel_rule(
name = name + "_as_target",
my_config_string = my_config_string,
)
```
```sh theme={null}
$ bazel build //myapp:sad_macro_less_sad
DEBUG: /myworkspace/myapp/defs.bzl:23:3: Invoking macro sad_macro_less_sad.
DEBUG: /myworkspace/myapp/defs.bzl:15:3: My name is sad_macro_less_sad with custom message: FIRST STRING.
```
### Why does select() always return true?
Because *macros* (but not rules) by definition
[can't evaluate `select()`s](#faq-select-macro), any attempt to do so
usually produces an error:
```sh theme={null}
ERROR: /myworkspace/myapp/BUILD:17:1: Traceback
(most recent call last):
File "/myworkspace/myapp/BUILD", line 17
my_custom_bazel_macro(name = "sad_macro", my_config_stri..."}))
File "/myworkspace/myapp/defs.bzl", line 4, in
my_custom_bazel_macro
my_config_string.upper()
type 'select' has no method upper().
```
Booleans are a special case that fail silently, so you should be particularly
vigilant with them:
```sh theme={null}
$ cat myapp/defs.bzl
def my_boolean_macro(boolval):
print("TRUE" if boolval else "FALSE")
$ cat myapp/BUILD
load("//myapp:defs.bzl", "my_boolean_macro")
my_boolean_macro(
boolval = select({
"//third_party/bazel_platforms/cpu:x86_32": True,
"//third_party/bazel_platforms/cpu:ppc": False,
}),
)
$ bazel build //myapp:all --cpu=x86
DEBUG: /myworkspace/myapp/defs.bzl:4:3: TRUE.
$ bazel build //mypro:all --cpu=ppc
DEBUG: /myworkspace/myapp/defs.bzl:4:3: TRUE.
```
This happens because macros don't understand the contents of `select()`.
So what they're really evaluting is the `select()` object itself. According to
[Pythonic](https://docs.python.org/release/2.5.2/lib/truth.html) design
standards, all objects aside from a very small number of exceptions
automatically return true.
### Can I read select() like a dict?
Macros [can't](#faq-select-macro) evaluate select(s) because macros evaluate before
Bazel knows what the build's command line parameters are. Can they at least read
the `select()`'s dictionary to, for example, add a suffix to each value?
Conceptually this is possible, but [it isn't yet a Bazel feature](https://github.com/bazelbuild/bazel/issues/8419).
What you *can* do today is prepare a straight dictionary, then feed it into a
`select()`:
```sh theme={null}
$ cat myapp/defs.bzl
def selecty_genrule(name, select_cmd):
for key in select_cmd.keys():
select_cmd[key] += " WITH SUFFIX"
native.genrule(
name = name,
outs = [name + ".out"],
srcs = [],
cmd = "echo " + select(select_cmd + {"//conditions:default": "default"})
+ " > $@"
)
$ cat myapp/BUILD
selecty_genrule(
name = "selecty",
select_cmd = {
"//third_party/bazel_platforms/cpu:x86_32": "x86 mode",
},
)
$ bazel build //testapp:selecty --cpu=x86 && cat bazel-genfiles/testapp/selecty.out
x86 mode WITH SUFFIX
```
If you'd like to support both `select()` and native types, you can do this:
```sh theme={null}
$ cat myapp/defs.bzl
def selecty_genrule(name, select_cmd):
cmd_suffix = ""
if type(select_cmd) == "string":
cmd_suffix = select_cmd + " WITH SUFFIX"
elif type(select_cmd) == "dict":
for key in select_cmd.keys():
select_cmd[key] += " WITH SUFFIX"
cmd_suffix = select(select_cmd + {"//conditions:default": "default"})
native.genrule(
name = name,
outs = [name + ".out"],
srcs = [],
cmd = "echo " + cmd_suffix + "> $@",
)
```
### Why doesn't select() work with bind()?
First of all, do not use `bind()`. It is deprecated in favor of `alias()`.
The technical answer is that [`bind()`](/reference/be/workspace#bind) is a repo
rule, not a BUILD rule.
Repo rules do not have a specific configuration, and aren't evaluated in
the same way as BUILD rules. Therefore, a `select()` in a `bind()` can't
actually evaluate to any specific branch.
Instead, you should use [`alias()`](/reference/be/general#alias), with a `select()` in
the `actual` attribute, to perform this type of run-time determination. This
works correctly, since `alias()` is a BUILD rule, and is evaluated with a
specific configuration.
You can even have a `bind()` target point to an `alias()`, if needed.
```sh theme={null}
$ cat WORKSPACE
workspace(name = "myapp")
bind(name = "openssl", actual = "//:ssl")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(name = "alternative", ...)
http_archive(name = "boringssl", ...)
$ cat BUILD
config_setting(
name = "alt_ssl",
define_values = {
"ssl_library": "alternative",
},
)
alias(
name = "ssl",
actual = select({
"//:alt_ssl": "@alternative//:ssl",
"//conditions:default": "@boringssl//:ssl",
}),
)
```
With this setup, you can pass `--define ssl_library=alternative`, and any target
that depends on either `//:ssl` or `//external:ssl` will see the alternative
located at `@alternative//:ssl`.
But really, stop using `bind()`.
### Why doesn't my select() choose what I expect?
If `//myapp:foo` has a `select()` that doesn't choose the condition you expect,
use [cquery](/query/cquery) and `bazel config` to debug:
If `//myapp:foo` is the top-level target you're building, run:
```sh theme={null}
$ bazel cquery //myapp:foo
//myapp:foo (12e23b9a2b534a)
```
If you're building some other target `//bar` that depends on
//myapp:foo somewhere in its subgraph, run:
```sh theme={null}
$ bazel cquery 'somepath(//bar, //myapp:foo)'
//bar:bar (3ag3193fee94a2)
//bar:intermediate_dep (12e23b9a2b534a)
//myapp:foo (12e23b9a2b534a)
```
The `(12e23b9a2b534a)` next to `//myapp:foo` is a *hash* of the
configuration that resolves `//myapp:foo`'s `select()`. You can inspect its
values with `bazel config`:
```sh theme={null}
$ bazel config 12e23b9a2b534a
BuildConfigurationValue 12e23b9a2b534a
Fragment com.google.devtools.build.lib.analysis.config.CoreOptions {
cpu: darwin
compilation_mode: fastbuild
...
}
Fragment com.google.devtools.build.lib.rules.cpp.CppOptions {
linkopt: [-Dfoo=bar]
...
}
...
```
Then compare this output against the settings expected by each `config_setting`.
`//myapp:foo` may exist in different configurations in the same build. See the
[cquery docs](/query/cquery) for guidance on using `somepath` to get the right
one.
Caution: To prevent restarting the Bazel server, invoke `bazel config` with the
same command line flags as the `bazel cquery`. The `config` command relies on
the configuration nodes from the still-running server of the previous command.
### Why doesn't `select()` work with platforms?
Bazel doesn't support configurable attributes checking whether a given platform
is the target platform because the semantics are unclear.
For example:
```py theme={null}
platform(
name = "x86_linux_platform",
constraint_values = [
"@platforms//cpu:x86",
"@platforms//os:linux",
],
)
cc_library(
name = "lib",
srcs = [...],
linkopts = select({
":x86_linux_platform": ["--enable_x86_optimizations"],
"//conditions:default": [],
}),
)
```
In this `BUILD` file, which `select()` should be used if the target platform has both the
`@platforms//cpu:x86` and `@platforms//os:linux` constraints, but is **not** the
`:x86_linux_platform` defined here? The author of the `BUILD` file and the user
who defined the separate platform may have different ideas.
#### What should I do instead?
Instead, define a `config_setting` that matches **any** platform with
these constraints:
```py theme={null}
config_setting(
name = "is_x86_linux",
constraint_values = [
"@platforms//cpu:x86",
"@platforms//os:linux",
],
)
cc_library(
name = "lib",
srcs = [...],
linkopts = select({
":is_x86_linux": ["--enable_x86_optimizations"],
"//conditions:default": [],
}),
)
```
This process defines specific semantics, making it clearer to users what
platforms meet the desired conditions.
#### What if I really, really want to `select` on the platform?
If your build requirements specifically require checking the platform, you
can flip the value of the `--platforms` flag in a `config_setting`:
```py theme={null}
config_setting(
name = "is_specific_x86_linux_platform",
values = {
"platforms": ["//package:x86_linux_platform"],
},
)
cc_library(
name = "lib",
srcs = [...],
linkopts = select({
":is_specific_x86_linux_platform": ["--enable_x86_optimizations"],
"//conditions:default": [],
}),
)
```
The Bazel team doesn't endorse doing this; it overly constrains your build and
confuses users when the expected condition does not match.
[BuildSettings]: /extending/config#user-defined-build-settings
# bazel mobile-install
Source: https://bazel.build/docs/mobile-install
Fast iterative development for Android
This page describes how `bazel mobile-install` makes iterative development
for Android much faster. It describes the benefits of this approach versus the
drawbacks of separate build and install steps.
## Summary
To install small changes to an Android app very quickly, do the following:
1. Find the `android_binary` rule of the app you want to install.
2. Connect your device to `adb`.
3. Run `bazel mobile-install :your_target`. App startup will be a little
slower than usual.
4. Edit the code or Android resources.
5. Run `bazel mobile-install :your_target`.
6. Enjoy a fast and minimal incremental installation!
Some command line options to Bazel that may be useful:
* `--adb` tells Bazel which adb binary to use
* `--adb_arg` can be used to add extra arguments to the command line of `adb`.
One useful application of this is to select which device you want to install
to if you have multiple devices connected to your workstation:
`bazel mobile-install :your_target -- --adb_arg=-s --adb_arg=`
When in doubt, look at the
[example](https://github.com/bazelbuild/rules_android/tree/main/examples/basicapp),
contact us on [Google Groups](https://groups.google.com/forum/#!forum/bazel-discuss),
or [file a GitHub issue](https://github.com/bazelbuild/rules_android/issues)
## Introduction
One of the most important attributes of a developer's toolchain is speed: there
is a world of difference between changing the code and seeing it run within a
second and having to wait minutes, sometimes hours, before you get any feedback
on whether your changes do what you expect them to.
Unfortunately, the traditional Android toolchain for building an .apk entails
many monolithic, sequential steps and all of these have to be done in order to
build an Android app. At Google, waiting five minutes to build a single-line
change was not unusual on larger projects like Google Maps.
`bazel mobile-install` makes iterative development for Android much faster by
using a combination of change pruning, work sharding, and clever manipulation of
Android internals, all without changing any of your app's code.
## Problems with traditional app installation
Building an Android app has some issues, including:
* Dexing. By default, the Dexer tool (historically `dx`, now `d8` or `r8`)
is invoked exactly once in the build and it does not know how to reuse work from
previous builds: it dexes every method again, even though only one method was
changed.
* Uploading data to the device. adb does not use the full bandwidth of a USB 2.0
connection, and larger apps can take a lot of time to upload. The entire app is
uploaded, even if only small parts have changed, for example, a resource or a
single method, so this can be a major bottleneck.
* Compilation to native code. Android L introduced ART, a new Android runtime,
which compiles apps ahead-of-time rather than compiling them just-in-time like
Dalvik. This makes apps much faster at the cost of longer installation
time. This is a good tradeoff for users because they typically install an app
once and use it many times, but results in slower development where an app is
installed many times and each version is run at most a handful of times.
## The approach of `bazel mobile-install`
`bazel mobile-install `makes the following improvements:
* Sharded desugaring and dexing. After building the app's Java code, Bazel
shards the class files into approximately equal-sized parts and invokes `d8`
separately on them. `d8` is not invoked on shards that did not change since
the last build. These shards are then compiled into separate sharded APKs.
* Incremental file transfer. Android resources, .dex files, and native
libraries are removed from the main .apk and are stored in under a separate
mobile-install directory. This makes it possible to update code and Android
resources independently without reinstalling the whole app. Thus,
transferring the files takes less time and only the .dex files that have
changed are recompiled on-device.
* Sharded installation. Mobile-install uses Android Studio's
[`apkdeployer`](https://maven.google.com/web/index.html?q=deployer#com.android.tools.apkdeployer:apkdeployer)
tool to combine sharded APKs on the connected device and provide a cohesive
experience.
### Sharded Dexing
Sharded dexing is reasonably straightforward: once the .jar files are built, a
[tool](https://github.com/bazelbuild/rules_android/blob/main/src/tools/java/com/google/devtools/build/android/ziputils/DexMapper.java)
shards them into separate .jar files of approximately equal size, then invokes
`d8` on those that were changed since the previous build. The logic that
determines which shards to dex is not specific to Android: it just uses the
general change pruning algorithm of Bazel.
The first version of the sharding algorithm simply ordered the .class files
alphabetically, then cut the list up into equal-sized parts, but this proved to
be suboptimal: if a class was added or removed (even a nested or an anonymous
one), it would cause all the classes alphabetically after it to shift by one,
resulting in dexing those shards again. Thus, it was decided to shard Java
packages rather than individual classes. Of course, this still results in
dexing many shards if a new package is added or removed, but that is much less
frequent than adding or removing a single class.
The number of shards is controlled by command-line configuration, using the
`--define=num_dex_shards=N` flag. In an ideal world, Bazel would
automatically determine how many shards are best, but Bazel currently must know
the set of actions (for example, commands to be executed during the build) before
executing any of them, so it cannot determine the optimal number of shards
because it doesn't know how many Java classes there will eventually be in the
app. Generally speaking, the more shards, the faster the build and the
installation will be, but the slower app startup becomes, because the dynamic
linker has to do more work. The sweet spot is usually between 10 and 50 shards.
### Incremental deployment
Incremental APK shard transfer and installation is now handled by the
`apkdeployer` utility described in ["The approach of mobile-install"](#approach-mobile-install).
Whereas earlier (native) versions of mobile-install required manually tracking
first-time installations and selectively apply the `--incremental`
flag on subsequent installation, the most recent version in [`rules_android`](https://github.com/bazelbuild/rules_android/tree/main/mobile_install)
has been greatly simplified. The same mobile-install
invocation can be used regardless of how many times the app has been installed
or reinstalled.
At a high level, the `apkdeployer` tool is a wrapper around various `adb`
sub-commands. The main entrypoint logic can be found in the
[`com.android.tools.deployer.Deployer`](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:deploy/deployer/src/main/java/com/android/tools/deployer/Deployer.java)
class, with other utility classes colocated in the same package.
The `Deployer` class ingests, among other things, a list of paths to split
APKs and a protobuf with information about the installation, and leverages
deployment features for [Android app bundles](https://developer.android.com/guide/app-bundle)
in order to create an install session and incrementally deploy app splits.
See the [`ApkPreInstaller`](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:deploy/deployer/src/main/java/com/android/tools/deployer/ApkPreInstaller.java)
and [`ApkInstaller`](https://cs.android.com/android-studio/platform/tools/base/+/mirror-goog-studio-main:deploy/deployer/src/main/java/com/android/tools/deployer/ApkInstaller.java)
classes for implementation details.
## Results
### Performance
In general, `bazel mobile-install` results in a 4x to 10x speedup of building
and installing large apps after a small change.
The following numbers were computed for a few Google products:
This, of course, depends on the nature of the change: recompilation after
changing a base library takes more time.
### Limitations
The tricks the stub application plays don't work in every case.
The following cases highlight where it does not work as expected:
* Mobile-install is only supported via the Starlark rules of `rules_android`.
See the ["brief history of mobile-install"](#mobile-install-history) for
more detail.
* Only devices running ART are supported. Mobile-install uses API and runtime features
that only exist on devices running ART, not Dalvik. Any Android runtime more
recent than Android L (API 21+) should be compatible.
* Bazel itself must be run with a tool Java runtime *and* language version
of 17 or higher.
* Bazel versions prior to 8.4.0 must specify some additional flags for
mobile-install. See [the Bazel Android tutorial](/start/android-app). These
flags inform Bazel where the Starlark mobile-install aspect is and which
rules are supported.
### A brief history of mobile-install
Earlier Bazel versions *natively* included built-in build and test rules for
popular languages and ecosystems such as C++, Java, and Android. These rules
were therefore referred to as *native* rules. Bazel 8 (released in 2024) removed
support for these rules because many of them had been migrated to the
[Starlark](/rules/language) language. See the ["Bazel 8.0 LTS blog post"](https://blog.bazel.build/2024/12/09/bazel-8-release.html)
for more details.
The legacy native Android rules also supported a legacy *native* version of
mobile-install functionality. This is referred to as "mobile-install v1" or
"native mobile-install" now. This functionality was deleted in Bazel 8, along
with the built-in Android rules.
Now, all mobile-install functionality, as well as all Android build and test
rules, are implemented in Starlark and reside in the `rules_android` GitHub
repository. The latest version is known as "mobile-install v3" or "MIv3".
*Naming note*: There was a "mobile-install **v2**" available only internally
at Google at one point, but this was never published externally, and only v3
continues to be used for both Google-internal and OSS rules\_android deployment.
# Sandboxing
Source: https://bazel.build/docs/sandboxing
This article covers sandboxing in Bazel and debugging your sandboxing
environment.
*Sandboxing* is a permission restricting strategy that isolates processes from
each other or from resources in a system. For Bazel, this means restricting file
system access.
Bazel's file system sandbox runs processes in a working directory that only
contains known inputs, such that compilers and other tools don't see source
files they should not access, unless they know the absolute paths to them.
Sandboxing doesn't hide the host environment in any way. Processes can freely
access all files on the file system. However, on platforms that support user
namespaces, processes can't modify any files outside their working directory.
This ensures that the build graph doesn't have hidden dependencies that could
affect the reproducibility of the build.
More specifically, Bazel constructs an `execroot/` directory for each action,
which acts as the action's work directory at execution time. `execroot/`
contains all input files to the action and serves as the container for any
generated outputs. Bazel then uses an operating-system-provided technique,
containers on Linux and `sandbox-exec` on macOS, to constrain the action within
`execroot/`.
## Reasons for sandboxing
* Without action sandboxing, Bazel doesn't know if a tool uses undeclared
input files (files that are not explicitly listed in the dependencies of an
action). When one of the undeclared input files changes, Bazel still
believes that the build is up-to-date and won’t rebuild the action. This can
result in an incorrect incremental build.
* Incorrect reuse of cache entries creates problems during remote caching. A
bad cache entry in a shared cache affects every developer on the project,
and wiping the entire remote cache is not a feasible solution.
* Sandboxing mimics the behavior of remote execution — if a build works well
with sandboxing, it will likely also work with remote execution. By making
remote execution upload all necessary files (including local tools), you can
significantly reduce maintenance costs for compile clusters compared to
having to install the tools on every machine in the cluster every time you
want to try out a new compiler or make a change to an existing tool.
## What sandbox strategy to use
You can choose which kind of sandboxing to use, if any, with the
[strategy flags](/docs/user-manual#strategy-options). Using the `sandboxed`
strategy makes Bazel pick one of the sandbox implementations listed below,
preferring an OS-specific sandbox to the less hermetic generic one.
[Persistent workers](/remote/persistent) run in a generic sandbox if you pass
the `--worker_sandboxing` flag. In addition to the plain boolean form, the flag
can be scoped to a specific worker-key mnemonic with
`--worker_sandboxing==` (for example
`--worker_sandboxing --worker_sandboxing=Javac=no` to sandbox all singleplex
workers except `Javac`; a later plain boolean value applies to all mnemonics
again).
The `local` (a.k.a. `standalone`) strategy does not do any kind of sandboxing.
It simply executes the action's command line with the working directory set to
the execroot of your workspace.
`processwrapper-sandbox` is a sandboxing strategy that does not require any
"advanced" features - it should work on any POSIX system out of the box. It
builds a sandbox directory consisting of symlinks that point to the original
source files, executes the action's command line with the working directory set
to this directory instead of the execroot, then moves the known output artifacts
out of the sandbox into the execroot and deletes the sandbox. This prevents the
action from accidentally using any input files that are not declared and from
littering the execroot with unknown output files.
`linux-sandbox` goes one step further and builds on top of the
`processwrapper-sandbox`. Similar to what Docker does under the hood, it uses
Linux Namespaces (User, Mount, PID, Network and IPC namespaces) to isolate the
action from the host. That is, it makes the entire filesystem read-only except
for the sandbox directory, so the action cannot accidentally modify anything on
the host filesystem. This prevents situations like a buggy test accidentally rm
-rf'ing your \$HOME directory. Optionally, you can also prevent the action from
accessing the network. `linux-sandbox` uses PID namespaces to prevent the action
from seeing any other processes and to reliably kill all processes (even daemons
spawned by the action) at the end.
`darwin-sandbox` is similar, but for macOS. It uses Apple's `sandbox-exec` tool
to achieve roughly the same as the Linux sandbox.
Both the `linux-sandbox` and the `darwin-sandbox` do not work in a "nested"
scenario due to restrictions in the mechanisms provided by the operating
systems. Because Docker also uses Linux namespaces for its container magic, you
cannot easily run `linux-sandbox` inside a Docker container, unless you use
`docker run --privileged`. On macOS, you cannot run `sandbox-exec` inside a
process that's already being sandboxed. Thus, in these cases, Bazel
automatically falls back to using `processwrapper-sandbox` (or `local` if no
sandbox strategy is supported).
If you want to prevent silent fallback and enforce a specific sandboxing
strategy — such as to ensure consistent, reproducible CI checks across
environments:
* **Enforce general sandboxing**: Pass `--spawn_strategy=sandboxed` (without
`local` in the fallback list). If sandboxing cannot execute, Bazel fails the
action rather than silently falling back to un-sandboxed execution (though
it still falls back to `processwrapper-sandbox` if OS namespaces are unsupported).
* **Enforce OS-level sandboxing (e.g. `linux-sandbox`)**: Explicitly request
the strategy by name, such as `--spawn_strategy=linux-sandbox` or
`--spawn_strategy=worker,linux-sandbox`. This is useful when builds or tests
strictly require kernel namespace features (such as network or mount isolation)
and must not quietly degrade to `processwrapper-sandbox`. If the requested
strategy is not supported on the host platform or environment, Bazel
immediately errors out at the start of the build (for example: `'linux-sandbox'
was requested for default strategies but no strategy with that identifier was registered`).
* **Best-effort sandboxing**: Pass multiple strategies separated by commas in
order of preference (for example, `--spawn_strategy=sandboxed,local` or
`--spawn_strategy=linux-sandbox,processwrapper-sandbox,local`). Bazel tries
each registered strategy in order.
* **Disable sandboxing completely**: Pass `--spawn_strategy=local`.
Dynamic execution usually requires sandboxing for local execution. To opt out,
pass the `--experimental_local_lockfree_output` flag. Dynamic execution silently
sandboxes [persistent workers](/remote/persistent).
## Downsides to sandboxing
* Sandboxing incurs extra setup and teardown cost. How big this cost is
depends on many factors, including the shape of the build and the
performance of the host OS. For Linux, sandboxed builds are rarely more than
a few percent slower. Setting `--reuse_sandbox_directories` can
mitigate the setup and teardown cost.
* Sandboxing effectively disables any cache the tool may have. You can
mitigate this by using [persistent workers](/remote/persistent), at
the cost of weaker sandbox guarantees.
* [Multiplex workers](/remote/multiplex) require explicit worker support
to be sandboxed. Workers that do not support multiplex sandboxing run as
singleplex workers under dynamic execution, which can cost extra memory.
## Debugging
Follow the strategies below to debug issues with sandboxing.
### Deactivated namespaces and containers
On some platforms, such as
[Google Kubernetes Engine](https://cloud.google.com/kubernetes-engine/)
cluster nodes, Docker containers, or Debian/Ubuntu distributions, user
namespaces or mount operations may be restricted by default due to security
policies:
* **User namespace clone sysctl**: If `/proc/sys/kernel/unprivileged_userns_clone`
exists and contains `0`, you can activate user namespaces on the host with:
```posix-terminal theme={null}
sudo sysctl kernel.unprivileged_userns_clone=1
```
* **Docker / container privileges**: `linux-sandbox` requires the `CLONE_NEWUSER`,
`CLONE_NEWNS`, `CLONE_NEWPID`, and `CLONE_NEWIPC` clone flags and mount namespace
isolation (`mount(..., MS_REC | MS_PRIVATE, ...)`). In unprivileged Docker
containers, default seccomp profiles block the necessary `clone` or `mount`
syscalls. To run `linux-sandbox` inside Docker, launch the container with
`docker run --privileged` or grant the necessary capabilities and relax the
seccomp filter:
```posix-terminal theme={null}
docker run --cap-add=SYS_ADMIN --security-opt seccomp=unconfined ...
```
* **Kubernetes Pod security**: In Kubernetes, Pods running Bazel with
`linux-sandbox` require `securityContext.privileged: true` or
`securityContext.capabilities.add: ["SYS_ADMIN"]` with an unconfined seccomp
profile. If running in an unprivileged container where user namespaces cannot
be enabled, either use `--spawn_strategy=processwrapper-sandbox` for portable
symlink-based sandboxing without namespaces, or run Bazel builds via remote
execution (`--spawn_strategy=remote`).
### Rule execution failures
The sandbox may fail to execute rules because of the system setup. If you see a
message like `namespace-sandbox.c:633: execvp(argv[0], argv): No such file or
directory`, try to deactivate the sandbox with `--strategy=Genrule=local` for
genrules, and `--spawn_strategy=local` for other rules.
### Detailed debugging for build failures
If your build failed, use `--verbose_failures` and `--sandbox_debug` to make
Bazel show the exact command it ran when your build failed, including the part
that sets up the sandbox.
Example error message:
```
ERROR: path/to/your/project/BUILD:1:1: compilation of rule
'//path/to/your/project:all' failed:
Sandboxed execution failed, which may be legitimate (such as a compiler error),
or due to missing dependencies. To enter the sandbox environment for easier
debugging, run the following command in parentheses. On command failure, a bash
shell running inside the sandbox will then automatically be spawned
namespace-sandbox failed: error executing command
(cd /some/path && \
exec env - \
LANG=en_US \
PATH=/some/path/bin:/bin:/usr/bin \
PYTHONPATH=/usr/local/some/path \
/some/path/namespace-sandbox @/sandbox/root/path/this-sandbox-name.params --
/some/path/to/your/some-compiler --some-params some-target)
```
You can now inspect the generated sandbox directory and see which files Bazel
created and run the command again to see how it behaves.
Note that Bazel does not delete the sandbox directory when you use
`--sandbox_debug`. Unless you are actively debugging, you should disable
`--sandbox_debug` because it fills up your disk over time.
# Commands and Options
Source: https://bazel.build/docs/user-manual
This page covers the options that are available with various Bazel commands,
such as `bazel build`, `bazel run`, and `bazel test`. This page is a companion
to the list of Bazel's commands in [Build with Bazel](/run/build).
## Target syntax
Some commands, like `build` or `test`, can operate on a list of targets. They
use a syntax more flexible than labels, which is documented in
[Specifying targets to build](/run/build#specifying-build-targets).
## Options
The following sections describe the options available during a
build. When `--long` is used on a help command, the on-line
help messages provide summary information about the meaning, type and
default value for each option.
Most options can only be specified once. When specified multiple times, the
last instance wins. Options that can be specified multiple times are
identified in the on-line help with the text 'may be used multiple times'.
### Package location
#### `--package_path`
**WARNING:** The `--package_path` option is deprecated. Bazel prefers packages
in the main repository to be under the workspace root.
This option specifies the set of directories that are searched to
find the BUILD file for a given package.
Bazel finds its packages by searching the package path. This is a colon
separated ordered list of bazel directories, each being the root of a
partial source tree.
*To specify a custom package path* using the `--package_path` option:
Package path elements may be specified in three formats:
1. If the first character is `/`, the path is absolute.
2. If the path starts with `%workspace%`, the path is taken relative
to the nearest enclosing bazel directory.
For instance, if your working directory
is `/home/bob/clients/bob_client/bazel/foo`, then the
string `%workspace%` in the package-path is expanded
to `/home/bob/clients/bob_client/bazel`.
3. Anything else is taken relative to the working directory.
This is usually not what you mean to do,
and may behave unexpectedly if you use Bazel from directories below the bazel workspace.
For instance, if you use the package-path element `.`,
and then cd into the directory
`/home/bob/clients/bob_client/bazel/foo`, packages
will be resolved from the
`/home/bob/clients/bob_client/bazel/foo` directory.
If you use a non-default package path, specify it in your
[Bazel configuration file](/run/bazelrc) for convenience.
*Bazel doesn't require any packages to be in the
current directory*, so you can do a build from an empty bazel
workspace if all the necessary packages can be found somewhere else
on the package path.
Example: Building from an empty client
#### `--deleted_packages`
This option specifies a comma-separated list of packages which Bazel
should consider deleted, and not attempt to load from any directory
on the package path. This can be used to simulate the deletion of packages without
actually deleting them. This option can be passed multiple times, in which case
the individual lists are concatenated.
### Error checking
These options control Bazel's error-checking and/or warnings.
#### `--[no]check_visibility`
If this option is set to false, visibility checks are demoted to warnings.
The default value of this option is true, so that by default, visibility
checking is done.
#### `--output_filter=regex`
The `--output_filter` option will only show build and compilation
warnings for targets that match the regular expression. If a target does not
match the given regular expression and its execution succeeds, its standard
output and standard error are thrown away.
Here are some typical values for this option:
### Tool flags
These options control which options Bazel will pass to other tools.
#### `--copt=cc-option`
This option takes an argument which is to be passed to the compiler.
The argument will be passed to the compiler whenever it is invoked
for preprocessing, compiling, and/or assembling C, C++, or
assembler code. It will not be passed when linking.
This option can be used multiple times. For example:
% bazel build --copt="-g0" --copt="-fpic" //foo
will compile the `foo` library without debug tables, generating
position-independent code.
Note: Changing `--copt` settings will force a recompilation
of all affected object files. Also note that copts values listed in specific
cc\_library or cc\_binary build rules will be placed on the compiler command line
*after* these options.
Warning: C++-specific options (such as `-fno-implicit-templates`)
should be specified in `--cxxopt`, not in
`--copt`. Likewise, C-specific options (such as -Wstrict-prototypes)
should be specified in `--conlyopt`, not in `copt`.
Similarly, compiler options that only have an
effect at link time (such as `-l`) should be specified in
`--linkopt`, not in `--copt`.
#### `--host_copt=cc-option`
This option takes an argument which is to be passed to the compiler for source files
that are compiled in the exec configuration. This is analogous to
the [`--copt`](#copt) option, but applies only to the
exec configuration.
#### `--host_conlyopt=cc-option`
This option takes an argument which is to be passed to the compiler for C source files
that are compiled in the exec configuration. This is analogous to
the [`--conlyopt`](#cconlyopt) option, but applies only
to the exec configuration.
#### `--host_cxxopt=cc-option`
This option takes an argument which is to be passed to the compiler for C++ source files
that are compiled in the exec configuration. This is analogous to
the [`--cxxopt`](#cxxopt) option, but applies only to the
exec configuration.
#### `--host_linkopt=linker-option`
This option takes an argument which is to be passed to the linker for source files
that are compiled in the exec configuration. This is analogous to
the [`--linkopt`](#linkopt) option, but applies only to
the exec configuration.
#### `--conlyopt=cc-option`
This option takes an argument which is to be passed to the compiler when compiling C source files.
This is similar to `--copt`, but only applies to C compilation,
not to C++ compilation or linking. So you can pass C-specific options
(such as `-Wno-pointer-sign`) using `--conlyopt`.
Note: copts parameters listed in specific cc\_library or cc\_binary build rules
are placed on the compiler command line *after* these options.
#### `--cxxopt=cc-option`
This option takes an argument which is to be passed to the compiler when
compiling C++ source files.
This is similar to `--copt`, but only applies to C++ compilation,
not to C compilation or linking. So you can pass C++-specific options
(such as `-fpermissive` or `-fno-implicit-templates`) using `--cxxopt`.
For example:
Note: copts parameters listed in specific cc\_library or cc\_binary build rules
are placed on the compiler command line *after* these options.
#### `--linkopt=linker-option`
This option takes an argument which is to be passed to the compiler when linking.
This is similar to `--copt`, but only applies to linking,
not to compilation. So you can pass compiler options that only make sense
at link time (such as `-lssp` or `-Wl,--wrap,abort`)
using `--linkopt`. For example:
Build rules can also specify link options in their attributes. This option's
settings always take precedence. Also see
[cc\_library.linkopts](/reference/be/c-cpp#cc_library.linkopts).
#### `--strip (always|never|sometimes)`
This option determines whether Bazel will strip debugging information from
all binaries and shared libraries, by invoking the linker with the `-Wl,--strip-debug` option.
`--strip=always` means always strip debugging information.
`--strip=never` means never strip debugging information.
The default value of `--strip=sometimes` means strip if the `--compilation_mode`
is `fastbuild`.
% bazel build --strip=always //foo:bar
will compile the target while stripping debugging information from all generated
binaries.
Note: If you want debugging information, it's not enough to disable stripping;
you also need to make sure that the debugging information was generated by the
compiler, which you can do by using either `-c dbg` or `--copt -g`.
Bazel's `--strip` option corresponds with ld's `--strip-debug` option:
it only strips debugging information. If for some reason you want to strip *all* symbols,
not just *debug* symbols, you would need to use ld's `--strip-all` option,
which you can do by passing `--linkopt=-Wl,--strip-all` to Bazel. Also be
aware that setting Bazel's `--strip` flag will override
`--linkopt=-Wl,--strip-all`, so you should only set one or the other.
If you are only building a single binary and want all symbols stripped, you could also
pass `--stripopt=--strip-all` and explicitly build the
`//foo:bar.stripped` version of the target. As described in the section on
`--stripopt`, this applies a strip action after the final binary is
linked rather than including stripping in all of the build's link actions.
#### `--stripopt=strip-option`
This is an additional option to pass to the `strip` command when generating
a [`*.stripped` binary](/reference/be/c-cpp#cc_binary_implicit_outputs). The default
is `-S -p`. This option can be used multiple times.
Note: `--stripopt` does not apply to the stripping of the main
binary with `[--strip](#flag--strip)=(always|sometimes)`.
#### `--fdo_instrument=profile-output-dir`
The `--fdo_instrument` option enables the generation of
FDO (feedback directed optimization) profile output when the
built C/C++ binary is executed. For GCC, the argument provided is used as a
directory prefix for a per-object file directory tree of .gcda files
containing profile information for each .o file.
Once the profile data tree has been generated, the profile tree
should be zipped up, and provided to the
`--fdo_optimize=profile-zip`
Bazel option to enable the FDO-optimized compilation.
For the LLVM compiler the argument is also the directory under which the raw LLVM profile
data file(s) is dumped. For example:
`--fdo_instrument=/path/to/rawprof/dir/`.
The options `--fdo_instrument` and `--fdo_optimize` cannot be used at the same time.
#### `--fdo_optimize=profile-zip`
The `--fdo_optimize` option enables the use of the
per-object file profile information to perform FDO (feedback
directed optimization) optimizations when compiling. For GCC, the argument
provided is the zip file containing the previously-generated file tree
of .gcda files containing profile information for each .o file.
Alternatively, the argument provided can point to an auto profile
identified by the extension .afdo.
Note: This option also accepts labels that resolve to source files. You
may need to add an `exports_files` directive to the corresponding package to
make the file visible to Bazel.
For the LLVM compiler the argument provided should point to the indexed LLVM
profile output file prepared by the llvm-profdata tool, and should have a .profdata
extension.
The options `--fdo_instrument` and `--fdo_optimize` cannot be used at the same time.
#### `--java_language_version=version`
This option specifies the version of Java sources. For example:
compiles and allows only constructs compatible with Java 8 specification.
Default value is 11.
Possible values are: 8, 9, 10, 11, 17, and 21 and may be extended by
registering custom Java toolchains using `default_java_toolchain`.
#### `--tool_java_language_version=version`
The Java language version used to build tools that are executed during a build.
Default value is 11.
#### `--java_runtime_version=version`
This option specifies the version of JVM to use to execute the code and run the tests. For
example:
% bazel run --java\_runtime\_version=remotejdk\_11 java/com/example/common/foo:java\_application
downloads JDK 11 from a remote repository and run the Java application using it.
Default value is `local_jdk`.
Possible values are: `local_jdk`, `local_jdk_version`,
`remotejdk_11`, `remotejdk_17`, and `remotejdk_21`.
You can extend the values by registering custom JVM using either
`local_java_repository` or `remote_java_repository` repository rules.
#### `--tool_java_runtime_version=version`
The version of JVM used to execute tools that are needed during a build.
Default value is `remotejdk_11`.
#### `--jvmopt=jvm-option`
This option allows option arguments to be passed to the Java VM. It can be used
with one big argument, or multiple times with individual arguments. For example:
will use the server VM for launching all Java binaries and set the
startup heap size for the VM to 256 MB.
#### `--javacopt=javac-option`
This option allows option arguments to be passed to javac. It can be used
with one big argument, or multiple times with individual arguments. For example:
will rebuild a java\_binary with the javac default debug info
(instead of the bazel default).
The option is passed to javac after the Bazel built-in default options for
javac and before the per-rule options. The last specification of
any option to javac wins. The default options for javac are:
-source 8 -target 8 -encoding UTF-8
Note: Changing `--javacopt` settings will force a recompilation
of all affected classes. Also note that javacopts parameters listed in
specific java\_library or java\_binary build rules will be placed on the javac
command line *after* these options.
#### `--strict_java_deps (default|strict|off|warn|error)`
This option controls whether javac checks for missing direct dependencies.
Java targets must explicitly declare all directly used targets as
dependencies. This flag instructs javac to determine the jars actually used
for type checking each java file, and warn/error if they are not the output
of a direct dependency of the current target.
* `off` means checking is disabled.
* `warn` means javac will generate standard java warnings of
type `[strict]` for each missing direct dependency.
* `default`, `strict` and `error` all
mean javac will generate errors instead of warnings, causing the current
target to fail to build if any missing direct dependencies are found.
This is also the default behavior when the flag is unspecified.
### Build semantics
These options affect the build commands and/or the output file contents.
#### `--compilation_mode (fastbuild|opt|dbg)` (-c)
The `--compilation_mode` option (often shortened to `-c`,
especially `-c opt`) takes an argument of `fastbuild`, `dbg`
or `opt`, and affects various C/C++ code-generation
options, such as the level of optimization and the completeness of
debug tables. Bazel uses a different output directory for each
different compilation mode, so you can switch between modes without
needing to do a full rebuild *every* time.
* `fastbuild` means build as fast as possible:
generate minimal debugging information (`-gmlt
-Wl,-S`), and don't optimize. This is the
default. Note: `-DNDEBUG` will **not** be set.
* `dbg` means build with debugging enabled (`-g`),
so that you can use gdb (or another debugger).
* `opt` means build with optimization enabled and
with `assert()` calls disabled (`-O2 -DNDEBUG`).
Debugging information will not be generated in `opt` mode
unless you also pass `--copt -g`.
#### `--cpu=cpu`
This option specifies the target CPU architecture to be used for
the compilation of binaries during the build.
Note: A particular combination of crosstool version, compiler version,
and target CPU is allowed only if it has been specified in the currently
used CROSSTOOL file.
#### `--action_env=VAR=VALUE`
Specifies the set of environment variables available during the execution of all actions.
Variables can be either specified by name, in which case the value will be taken from the
invocation environment, or by the `name=value` pair which sets the value independent of the
invocation environment.
This `--action_env` flag can be specified multiple times. If a value is assigned to the same
variable across multiple `--action_env` flags, the latest assignment wins.
#### `--experimental_action_listener=label`
Warning: Extra actions are deprecated. Use
[aspects](/extending/aspects)
instead.
The `experimental_action_listener` option instructs Bazel to use
details from the [`action_listener`](/reference/be/extra-actions#action_listener) rule specified by label to
insert [`extra_actions`](/reference/be/extra-actions#extra_action) into the build graph.
#### `--[no]experimental_extra_action_top_level_only`
Warning: Extra actions are deprecated. Use
[aspects](/extending/aspects) instead.
If this option is set to true, extra actions specified by the
[ `--experimental_action_listener`](#experimental-action-listener) command
line option will only be scheduled for top level targets.
#### `--experimental_extra_action_filter=regex`
Warning: Extra actions are deprecated. Use
[aspects](/extending/aspects) instead.
The `experimental_extra_action_filter` option instructs Bazel to
filter the set of targets to schedule `extra_actions` for.
This flag is only applicable in combination with the
[`--experimental_action_listener`](#experimental-action-listener) flag.
By default all `extra_actions` in the transitive closure of the
requested targets-to-build get scheduled for execution.
`--experimental_extra_action_filter` will restrict scheduling to
`extra_actions` of which the owner's label matches the specified
regular expression.
The following example will limit scheduling of `extra_actions`
to only apply to actions of which the owner's label contains '/bar/':
#### `--host_cpu=cpu`
This option specifies the name of the CPU architecture that should be
used to build host tools.
#### `--android_platforms=platform[,platform]*`
The platforms to build the transitive `deps` of
`android_binary` rules (specifically for native dependencies like C++). For
example, if a `cc_library` appears in the transitive `deps` of an
`android_binary` rule it is be built once for each platform specified with
`--android_platforms` for the `android_binary` rule, and included in the final
output.
There is no default value for this flag: a custom Android platform must be
defined and used.
One `.so` file is created and packaged in the APK for each platform specified
with `--android_platforms`. The `.so` file's name prefixes the name of the
`android_binary` rule with "lib". For example, if the name of the
`android_binary` is "foo", then the file is `libfoo.so`.
#### `--per_file_copt=[+-]regex[,[+-]regex]...@option[,option]...`
When present, any C++ file with a label or an execution path matching one of the inclusion regex
expressions and not matching any of the exclusion expressions will be built
with the given options. The label matching uses the canonical form of the label
(i.e //`package`:`label_name`).
The execution path is the relative path to your workspace directory including the base name
(including extension) of the C++ file. It also includes any platform dependent prefixes.
Note: If only one of the label or the execution path matches the options will be used.
To match the generated files (such as genrule outputs)
Bazel can only use the execution path. In this case the regexp shouldn't start with '//'
since that doesn't match any execution paths. Package names can be used like this:
`--per_file_copt=base/.*\.pb\.cc@-g0`. This will match every
`.pb.cc` file under a directory called `base`.
This option can be used multiple times.
The option is applied regardless of the compilation mode used. For example, it is possible
to compile with `--compilation_mode=opt` and selectively compile some
files with stronger optimization turned on, or with optimization disabled.
**Caveat**: If some files are selectively compiled with debug symbols the symbols
might be stripped during linking. This can be prevented by setting
`--strip=never`.
**Syntax**: `[+-]regex[,[+-]regex]...@option[,option]...` Where
`regex` stands for a regular expression that can be prefixed with
a `+` to identify include patterns and with `-` to identify
exclude patterns. `option` stands for an arbitrary option that is passed
to the C++ compiler. If an option contains a `,` it has to be quoted like so
`\,`. Options can also contain `@`, since only the first
`@` is used to separate regular expressions from options.
**Example**:
`--per_file_copt=//foo:.*\.cc,-//foo:file\.cc@-O0,-fprofile-arcs`
adds the `-O0` and the `-fprofile-arcs` options to the command
line of the C++ compiler for all `.cc` files in `//foo/` except `file.cc`.
#### `--dynamic_mode=mode`
Determines whether C++ binaries will be linked dynamically, interacting with
the [linkstatic attribute](/reference/be/c-cpp#cc_binary.linkstatic) on build rules.
Modes:
* `default`: Allows bazel to choose whether to link dynamically.
See [linkstatic](/reference/be/c-cpp#cc_binary.linkstatic) for more
information.
* `fully`: Links all targets dynamically. This will speed up
linking time, and reduce the size of the resulting binaries.
* `off`: Links all targets in
[mostly static](/reference/be/c-cpp#cc_binary.linkstatic) mode.
If `-static` is set in linkopts, targets will change to fully static.
#### `--fission (yes|no|[dbg][,opt][,fastbuild])`
Enables [Fission](https://gcc.gnu.org/wiki/DebugFission),
which writes C++ debug information to dedicated .dwo files instead of .o files, where it would
otherwise go. This substantially reduces the input size to links and can reduce link times.
When set to `[dbg][,opt][,fastbuild]` (example:
`--fission=dbg,fastbuild`), Fission is enabled
only for the specified set of compilation modes. This is useful for bazelrc
settings. When set to `yes`, Fission is enabled
universally. When set to `no`, Fission is disabled
universally. Default is no.
#### `--force_ignore_dash_static`
If this flag is set, any `-static` options in linkopts of
`cc_*` rules BUILD files are ignored. This is only intended as a
workaround for C++ hardening builds.
#### `--[no]force_pic`
If enabled, all C++ compilations produce position-independent code ("-fPIC"),
links prefer PIC pre-built libraries over non-PIC libraries, and links produce
position-independent executables ("-pie"). Default is disabled.
Note: Dynamically linked binaries (for example `--dynamic_mode fully`)
generate PIC code regardless of this flag's setting. So this flag is for cases
where users want PIC code explicitly generated for static links.
#### `--android_resource_shrinking`
Selects whether to perform resource shrinking for android\_binary rules. Sets the default for the
[shrink\_resources attribute](/reference/be/android#android_binary.shrink_resources) on
android\_binary rules; see the documentation for that rule for further details. Defaults to off.
#### `--custom_malloc=malloc-library-target`
When specified, always use the given malloc implementation, overriding all
`malloc="target"` attributes, including in those targets that use the
default (by not specifying any `malloc`).
#### `--crosstool_top=label`
This option specifies the location of the crosstool compiler suite
to be used for all C++ compilation during a build. Bazel will look in that
location for a CROSSTOOL file and uses that to automatically determine
settings for `--compiler`.
#### `--host_crosstool_top=label`
If not specified, Bazel uses the value of `--crosstool_top` to compile
code in the exec configuration, such as tools run during the build. The main purpose of this flag
is to enable cross-compilation.
#### `--apple_crosstool_top=label`
The crosstool to use for compiling C/C++ rules in the transitive `deps` of
objc\_*, ios\_\_*, and apple\_\* rules. For those targets, this flag overwrites
`--crosstool_top`.
#### `--compiler=version`
This option specifies the C/C++ compiler version (such as `gcc-4.1.0`)
to be used for the compilation of binaries during the build. If you want to
build with a custom crosstool, you should use a CROSSTOOL file instead of
specifying this flag.
Note: Only certain combinations of crosstool version, compiler version,
and target CPU are allowed.
#### `--android_sdk=label`
Deprecated. This shouldn't be directly specified.
This option specifies the Android SDK/platform toolchain
and Android runtime library that will be used to build any Android-related
rule.
The Android SDK will be automatically selected if an `android_sdk_repository`
rule is defined in the WORKSPACE file.
#### `--java_toolchain=label`
No-op. Kept only for backwards compatibility.
#### `--host_java_toolchain=label`
No-op. Kept only for backwards compatibility.
#### `--javabase=(label)`
No-op. Kept only for backwards compatibility.
#### `--host_javabase=label`
No-op. Kept only for backwards compatibility.
### Execution strategy
These options affect how Bazel will execute the build.
They should not have any significant effect on the output files
generated by the build. Typically their main effect is on the
speed of the build.
#### `--spawn_strategy=strategy`
This option controls where and how commands are executed.
* `standalone` causes commands to be executed as local subprocesses. This value is
deprecated. Please use `local` instead.
* `sandboxed` causes commands to be executed inside a sandbox on the local machine.
This requires that all input files, data dependencies and tools are listed as direct
dependencies in the `srcs`, `data` and `tools` attributes.
Bazel enables local sandboxing by default, on systems that support sandboxed execution.
* `processwrapper-sandbox` causes commands to be executed inside a portable symlink-based
sandbox without OS-specific namespace or container mechanisms.
* `linux-sandbox` causes commands to be executed inside a Linux namespace sandbox (using
User, Mount, PID, Network, and IPC namespaces).
* `darwin-sandbox` causes commands to be executed inside a macOS sandbox using `sandbox-exec`.
* `windows-sandbox` causes commands to be executed inside a Windows sandbox.
* `local` causes commands to be executed as local subprocesses.
* `worker` causes commands to be executed using a persistent worker, if available.
* `docker` causes commands to be executed inside a docker sandbox on the local machine.
This requires that docker is installed.
* `remote` causes commands to be executed remotely; this is only available if a
remote executor has been configured separately.
#### `--strategy mnemonic=strategy`
This option controls where and how commands are executed, overriding the
[--spawn\_strategy](#spawn-strategy) (and
[--genrule\_strategy](#genrule-strategy) with mnemonic
Genrule) on a per-mnemonic basis. See
[--spawn\_strategy](#spawn-strategy) for the supported
strategies and their effects.
#### `--strategy_regexp==`
This option specifies which strategy should be used to execute commands that have descriptions
matching a certain `regex_filter`. See
[--per\_file\_copt](#per-file-copt) for details on
regex\_filter matching. See
[--spawn\_strategy](#spawn-strategy) for the supported
strategies and their effects.
The last `regex_filter` that matches the description is used. This option overrides
other flags for specifying strategy.
* Example: `--strategy_regexp=//foo.*\\.cc,-//foo/bar=local` means to run actions using
`local` strategy if their descriptions match //foo.\*.cc but not //foo/bar.
* Example:
`--strategy_regexp='Compiling.*/bar=local' --strategy_regexp=Compiling=sandboxed`
runs 'Compiling //foo/bar/baz' with the `sandboxed` strategy, but reversing
the order runs it with `local`.
* Example: `--strategy_regexp='Compiling.*/bar=local,sandboxed'` runs
'Compiling //foo/bar/baz' with the `local` strategy and falls back to
`sandboxed` if it fails.
#### `--genrule_strategy=strategy`
This is a deprecated short-hand for `--strategy=Genrule=strategy`.
#### `--jobs=n` (-j)
This option, which takes an integer argument, specifies a limit on
the number of jobs that should be executed concurrently during the
execution phase of the build.
Note : The number of concurrent jobs that Bazel will run
is determined not only by the `--jobs` setting, but also
by Bazel's scheduler, which tries to avoid running concurrent jobs
that will use up more resources (RAM or CPU) than are available,
based on some (very crude) estimates of the resource consumption
of each job. The behavior of the scheduler can be controlled by
the `--local_resources` option.
#### `--progress_report_interval=n`
Bazel periodically prints a progress report on jobs that are not
finished yet (such as long running tests). This option sets the
reporting frequency, progress will be printed every `n`
seconds.
The default is 0, that means an incremental algorithm: the first
report will be printed after 10 seconds, then 30 seconds and after
that progress is reported once every minute.
When bazel is using cursor control, as specified by
[`--curses`](#curses), progress is reported every second.
#### `--local_resources resources or resource expression`
These options specify the amount of local resources (RAM in MB and number of CPU logical cores)
that Bazel can take into consideration when scheduling build and test activities to run locally. They take
an float, or a keyword (HOST\_RAM or HOST\_CPUS) optionally followed by `[-|*`float`]`
(for example, `--local_resources=cpu=2`, `--local_resources=memory=HOST_RAM*.5`,
`--local_resources=cpu=HOST_CPUS-1`).
The flags are independent; one or both may be set. By default, Bazel estimates
the amount of RAM and number of CPU cores directly from the local system's configuration.
#### `--[no]build_runfile_links`
This option, which is enabled by default, specifies whether the runfiles
symlinks for tests and binaries should be built in the output directory.
Using `--nobuild_runfile_links` can be useful
to validate if all targets compile without incurring the overhead
for building the runfiles trees.
When tests (or applications) are executed, their run-time data
dependencies are gathered together in one place. Within Bazel's
output tree, this "runfiles" tree is typically rooted as a sibling of
the corresponding binary or test.
During test execution, runfiles may be accessed using paths of the form
`$TEST_SRCDIR/canonical_repo_name/packagename/filename`.
The runfiles tree ensures that tests have access to all the files
upon which they have a declared dependence, and nothing more. By
default, the runfiles tree is implemented by constructing a set of
symbolic links to the required files. As the set of links grows, so
does the cost of this operation, and for some large builds it can
contribute significantly to overall build time, particularly because
each individual test (or application) requires its own runfiles tree.
#### `--[no]build_runfile_manifests`
This option, which is enabled by default, specifies whether runfiles manifests
should be written to the output tree.
Disabling it implies `--nobuild_runfile_links`.
It can be disabled when executing tests remotely, as runfiles trees will
be created remotely from in-memory manifests.
#### `--[no]discard_analysis_cache`
When this option is enabled, Bazel will discard the analysis cache
right before execution starts, thus freeing up additional memory
(around 10%) for the [execution phase](/run/build#execution).
The drawback is that further incremental builds will be slower. See also
[memory-saving mode](/configure/memory).
#### `--[no]keep_going` (-k)
As in GNU Make, the execution phase of a build stops when the first
error is encountered. Sometimes it is useful to try to build as
much as possible even in the face of errors. This option enables
that behavior, and when it is specified, the build will attempt to
build every target whose prerequisites were successfully built, but
will ignore errors.
While this option is usually associated with the execution phase of
a build, it also affects the analysis phase: if several targets are
specified in a build command, but only some of them can be
successfully analyzed, the build will stop with an error
unless `--keep_going` is specified, in which case the
build will proceed to the execution phase, but only for the targets
that were successfully analyzed.
#### `--[no]use_ijars`
This option changes the way `java_library` targets are
compiled by Bazel. Instead of using the output of a
`java_library` for compiling dependent
`java_library` targets, Bazel will create interface jars
that contain only the signatures of non-private members (public,
protected, and default (package) access methods and fields) and use
the interface jars to compile the dependent targets. This makes it
possible to avoid recompilation when changes are only made to
method bodies or private members of a class.
Note: Using `--use_ijars` might give you a different
error message when you are accidentally referring to a non visible
member of another class: Instead of getting an error that the member
is not visible you will get an error that the member does not exist.
Changing the `--use_ijars` setting will force a recompilation of all affected
classes.
#### `--[no]interface_shared_objects`
This option enables *interface shared objects*, which makes binaries and
other shared libraries depend on the *interface* of a shared object,
rather than its implementation. When only the implementation changes, Bazel
can avoid rebuilding targets that depend on the changed shared library
unnecessarily.
### Output selection
These options determine what to build or test.
#### `--[no]build`
This option causes the execution phase of the build to occur; it is
on by default. When it is switched off, the execution phase is
skipped, and only the first two phases, loading and analysis, occur.
This option can be useful for validating BUILD files and detecting
errors in the inputs, without actually building anything.
#### `--[no]build_tests_only`
If specified, Bazel will build only what is necessary to run the `*_test`
and `test_suite` rules that were not filtered due to their
[size](#test-size-filters),
[timeout](#test-timeout-filters),
[tag](#test-tag-filters), or
[language](#test-lang-filters).
If specified, Bazel will ignore other targets specified on the command line.
By default, this option is disabled and Bazel will build everything
requested, including `*_test` and `test_suite` rules that are filtered out from
testing. This is useful because running
`bazel test --build_tests_only foo/...` may not detect all build
breakages in the `foo` tree.
#### `--[no]check_up_to_date`
This option causes Bazel not to perform a build, but merely check
whether all specified targets are up-to-date. If so, the build
completes successfully, as usual. However, if any files are out of
date, instead of being built, an error is reported and the build
fails. This option may be useful to determine whether a build has
been performed more recently than a source edit (for example, for pre-submit
checks) without incurring the cost of a build.
See also [`--check_tests_up_to_date`](#check-tests-up-to-date).
#### `--[no]compile_one_dependency`
Compile a single dependency of the argument files. This is useful for
syntax checking source files in IDEs, for example, by rebuilding a single
target that depends on the source file to detect errors as early as
possible in the edit/build/test cycle. This argument affects the way all
non-flag arguments are interpreted: each argument must be a
file target label or a plain filename relative to the current working
directory, and one rule that depends on each source filename is built. For
C++ and Java
sources, rules in the same language space are preferentially chosen. For
multiple rules with the same preference, the one that appears first in the
BUILD file is chosen. An explicitly named target pattern which does not
reference a source file results in an error.
#### `--save_temps`
The `--save_temps` option causes temporary outputs from the compiler to be
saved. These include .s files (assembler code), .i (preprocessed C) and .ii
(preprocessed C++) files. These outputs are often useful for debugging. Temps will only be
generated for the set of targets specified on the command line.
Note: The implementation of `--save_temps` does not use the compiler's
`-save-temps` flag. Instead, there are two passes, one with `-S`
and one with `-E`. A consequence of this is that if your build fails,
Bazel may not yet have produced the ".i" or ".ii" and ".s" files.
If you're trying to use `--save_temps` to debug a failed compilation,
you may need to also use `--keep_going` so that Bazel will still try to
produce the preprocessed files after the compilation fails.
The `--save_temps` flag currently works only for cc\_\* rules.
To ensure that Bazel prints the location of the additional output files, check that
your [`--show_result n`](#show-result)
setting is high enough.
#### `--build_tag_filters=tag[,tag]*`
If specified, Bazel will build only targets that have at least one required tag
(if any of them are specified) and does not have any excluded tags. Build tag
filter is specified as comma delimited list of tag keywords, optionally
preceded with '-' sign used to denote excluded tags. Required tags may also
have a preceding '+' sign.
When running tests, Bazel ignores `--build_tag_filters` for test targets,
which are built and run even if they do not match this filter. To avoid building them, filter
test targets using `--test_tag_filters` or by explicitly excluding them.
#### `--test_size_filters=size[,size]*`
If specified, Bazel will test (or build if `--build_tests_only`
is also specified) only test targets with the given size. Test size filter
is specified as comma delimited list of allowed test size values (small,
medium, large or enormous), optionally preceded with '-' sign used to denote
excluded test sizes. For example,
% bazel test --test\_size\_filters=small,medium //foo:all
and
% bazel test --test\_size\_filters=-large,-enormous //foo:all
will test only small and medium tests inside //foo.
By default, test size filtering is not applied.
#### `--test_timeout_filters=timeout[,timeout]*`
If specified, Bazel will test (or build if `--build_tests_only`
is also specified) only test targets with the given timeout. Test timeout filter
is specified as comma delimited list of allowed test timeout values (short,
moderate, long or eternal), optionally preceded with '-' sign used to denote
excluded test timeouts. See [--test\_size\_filters](#test-size-filters)
for example syntax.
By default, test timeout filtering is not applied.
#### `--test_tag_filters=tag[,tag]*`
If specified, Bazel will test (or build if `--build_tests_only`
is also specified) only test targets that have at least one required tag
(if any of them are specified) and does not have any excluded tags. Test tag
filter is specified as comma delimited list of tag keywords, optionally
preceded with '-' sign used to denote excluded tags. Required tags may also
have a preceding '+' sign.
For example,
% bazel test --test\_tag\_filters=performance,stress,-flaky //myproject:all
will test targets that are tagged with either `performance` or
`stress` tag but are **not** tagged with the `flaky` tag.
By default, test tag filtering is not applied. Note that you can also filter
on test's `size` and `local` tags in
this manner.
#### `--test_lang_filters=string[,string]*`
Specifies a comma-separated list of strings referring to names of test rule
classes. To refer to the rule class `foo_test`, use the string "foo". Bazel will
test (or build if `--build_tests_only` is also specified) only
targets of the referenced rule classes. To instead exclude those targets, use
the string "-foo". For example,
% bazel test --test\_lang\_filters=foo,bar //baz/...
will test only targets that are instances of `foo_test` or `bar_test` in
`//baz/...`, while
% bazel test --test\_lang\_filters=-foo,-bar //baz/...
will test all the targets in `//baz/...` except for the `foo_test` and
`bar_test` instances.
Tip: You can use `bazel query --output=label_kind "//p:t"` to
learn the rule class name of the target `//p:t`. And you can
look at the pair of instantiation stacks in the output of
`bazel query --output=build "//p:t"` to learn why that target
is an instance of that rule class.
Warning: The option name "--test\_lang\_filter" is vestigal and is therefore
unfortunately misleading; don't make assumptions about the semantics based on
the name.
#### `--test_filter=filter-expression`
Specifies a filter that the test runner may use to pick a subset of tests for
running. All targets specified in the invocation are built, but depending on
the expression only some of them may be executed; in some cases, only certain
test methods are run.
The particular interpretation of filter-expression is up to
the test framework responsible for running the test. It may be a glob,
substring, or regexp. `--test_filter` is a convenience
over passing different `--test_arg` filter arguments,
but not all frameworks support it.
### Verbosity
These options control the verbosity of Bazel's output,
either to the terminal, or to additional log files.
#### `--explain=logfile`
This option, which requires a filename argument, causes the
dependency checker in `bazel build`'s execution phase to
explain, for each build step, either why it is being executed, or
that it is up-to-date. The explanation is written
to *logfile*.
If you are encountering unexpected rebuilds, this option can help to
understand the reason. Add it to your `.bazelrc` so that
logging occurs for all subsequent builds, and then inspect the log
when you see an execution step executed unexpectedly. This option
may carry a small performance penalty, so you might want to remove
it when it is no longer needed.
#### `--verbose_explanations`
This option increases the verbosity of the explanations generated
when the [--explain](#explain) option is enabled.
In particular, if verbose explanations are enabled,
and an output file is rebuilt because the command used to
build it has changed, then the output in the explanation file will
include the full details of the new command (at least for most
commands).
Using this option may significantly increase the length of the
generated explanation file and the performance penalty of using
`--explain`.
If `--explain` is not enabled, then
`--verbose_explanations` has no effect.
#### `--profile=file`
This option, which takes a filename argument, causes Bazel to write
profiling data into a file. The build profile can be useful in understanding
where Bazel's `build` command is spending its time. See
[JSON trace profile](/advanced/performance/json-trace-profile) for profile
format and tooling details.
#### `--[no]show_loading_progress`
This option causes Bazel to output package-loading progress
messages. If it is disabled, the messages won't be shown.
#### `--[no]show_progress`
This option causes progress messages to be displayed; it is on by
default. When disabled, progress messages are suppressed.
#### `--show_progress_rate_limit=n`
This option causes bazel to display at most one progress message per `n` seconds,
where n is a real number.
The default value for this option is 0.02, meaning bazel will limit the progress
messages to one per every 0.02 seconds.
#### `--show_result=n`
This option controls the printing of result information at the end
of a `bazel build` command. By default, if a single
build target was specified, Bazel prints a message stating whether
or not the target was successfully brought up-to-date, and if so,
the list of output files that the target created. If multiple
targets were specified, result information is not displayed.
While the result information may be useful for builds of a single
target or a few targets, for large builds (such as an entire top-level
project tree), this information can be overwhelming and distracting;
this option allows it to be controlled. `--show_result`
takes an integer argument, which is the maximum number of targets
for which full result information should be printed. By default,
the value is 1. Above this threshold, no result information is
shown for individual targets. Thus zero causes the result
information to be suppressed always, and a very large value causes
the result to be printed always.
Users may wish to choose a value in-between if they regularly
alternate between building a small group of targets (for example,
during the compile-edit-test cycle) and a large group of targets
(for example, when establishing a new workspace or running
regression tests). In the former case, the result information is
very useful whereas in the latter case it is less so. As with all
options, this can be specified implicitly via
the [`.bazelrc`](/run/bazelrc) file.
The files are printed so as to make it easy to copy and paste the
filename to the shell, to run built executables. The "up-to-date"
or "failed" messages for each target can be easily parsed by scripts
which drive a build.
#### `--sandbox_debug`
This option causes Bazel to print extra debugging information when using sandboxing for action
execution. This option also preserves sandbox directories, so that the files visible to actions
during execution can be examined.
#### `--subcommands` (`-s`)
This option causes Bazel's execution phase to print the full command line
for each command prior to executing it.
```
>>>> # //examples/cpp:hello-world [action 'Linking examples/cpp/hello-world']
(cd /home/johndoe/.cache/bazel/_bazel_johndoe/4c084335afceb392cfbe7c31afee3a9f/bazel && \
exec env - \
/usr/bin/gcc -o bazel-out/local-fastbuild/bin/examples/cpp/hello-world -B/usr/bin/ -Wl,-z,relro,-z,now -no-canonical-prefixes -pass-exit-codes -Wl,-S -Wl,@bazel-out/local_linux-fastbuild/bin/examples/cpp/hello-world-2.params)
```
Where possible, commands are printed in a Bourne shell compatible syntax,
so that they can be easily copied and pasted to a shell command prompt.
(The surrounding parentheses are provided to protect your shell from the
`cd` and `exec` calls; be sure to copy them!)
However some commands are implemented internally within Bazel, such as
creating symlink trees. For these there's no command line to display.
`--subcommands=pretty_print` may be passed to print
the arguments of the command as a list rather than as a single line. This may
help make long command lines more readable.
See also [--verbose\_failures](#verbose-failures), below.
For logging subcommands to a file in a tool-friendly format, see
[--execution\_log\_json\_file](/reference/command-line-reference#flag--execution_log_json_file)
and
[--execution\_log\_binary\_file](/reference/command-line-reference#flag--execution_log_binary_file).
#### `--verbose_failures`
This option causes Bazel's execution phase to print the full command line
for commands that failed. This can be invaluable for debugging a
failing build.
Failing commands are printed in a Bourne shell compatible syntax, suitable
for copying and pasting to a shell prompt.
### Workspace status
Use these options to "stamp" Bazel-built binaries: to embed additional information into the
binaries, such as the source control revision or other workspace-related information. You can use
this mechanism with rules that support the `stamp` attribute, such as
`genrule`, `cc_binary`, and more.
#### `--workspace_status_command=program`
This flag lets you specify a binary that Bazel runs before each build. The program can report
information about the status of the workspace, such as the current source control revision.
The flag's value must be a path to a native program. On Linux/macOS this may be any executable.
On Windows this must be a native binary, typically an ".exe", ".bat", or a ".cmd" file.
The program should print zero or more key/value pairs to standard output, one entry on each line,
then exit with zero (otherwise the build fails). The key names can be anything but they may only
use upper case letters and underscores. The first space after the key name separates it from the
value. The value is the rest of the line (including additional whitespaces). Neither the key nor
the value may span multiple lines. Keys must not be duplicated.
Bazel partitions the keys into two buckets: "stable" and "volatile". (The names "stable" and
"volatile" are a bit counter-intuitive, so don't think much about them.)
Bazel then writes the key-value pairs into two files:
* `bazel-out/stable-status.txt`
contains all keys and values where the key's name starts with `STABLE_`
* `bazel-out/volatile-status.txt`
contains the rest of the keys and their values
The contract is:
* "stable" keys' values should change rarely, if possible. If the contents of
`bazel-out/stable-status.txt`
change, Bazel invalidates the actions that depend on them. In
other words, if a stable key's value changes, Bazel will rerun stamped actions.
Therefore the stable status should not contain things like timestamps, because they change all
the time, and would make Bazel rerun stamped actions with each build.
Bazel always outputs the following stable keys:
* `BUILD_EMBED_LABEL`: value of `--embed_label`
* `BUILD_HOST`: the name of the host machine that Bazel is running on
* `BUILD_USER`: the name of the user that Bazel is running as
* "volatile" keys' values may change often. Bazel expects them to change all the time, like
timestamps do, and duly updates the
`bazel-out/volatile-status.txt`
file. In order to avoid
rerunning stamped actions all the time though, **Bazel pretends that the volatile file never
changes**. In other words, if the volatile status file is the only file whose contents has
changed, Bazel will not invalidate actions that depend on it. If other inputs of the actions
have changed, then Bazel reruns that action, and the action will see the updated volatile
status, but just the volatile status changing alone will not invalidate the action.
Bazel always outputs the following volatile keys:
* `BUILD_TIMESTAMP`: time of the build in seconds since the Unix Epoch (the value
of `System.currentTimeMillis()` divided by a thousand)
* `FORMATTED_DATE`: time of the build Formatted as
`yyyy MMM d HH mm ss EEE`(for example 2023 Jun 2 01 44 29 Fri) in UTC.
On Linux/macOS you can pass `--workspace_status_command=/bin/true` to
disable retrieving workspace status, because `true` does nothing, successfully (exits
with zero) and prints no output. On Windows you can pass the path of MSYS's `true.exe`
for the same effect.
If the workspace status command fails (exits non-zero) for any reason, the build will fail.
Example program on Linux using Git:
Pass this program's path with `--workspace_status_command`, and the stable status file
will include the STABLE lines and the volatile status file will include the rest of the lines.
#### Using workspace status in your build
The status key-value pairs can be used in your build through Starlark actions
and templates. Many binary or 'top-level' rules, and other rules like
`genrule`, support the `stamp` attribute, which can embed workspace status
information into the compiled binaries.
For example, when using `cc_binary` with `stamp = 1`, Bazel will automatically
make the workspace status available to the build. You can then access these
values through template files:
```python theme={null}
# In your BUILD file
cc_binary(
name = "my_binary",
srcs = ["main.cc"],
stamp = 1, # Enable stamping to include workspace status
)
# For custom use of workspace status, you can use ctx.actions.declare_file
# and read the status files from ctx.workspace_status
```
For Java projects, you can use the `bazel_java_build_info` rule to generate
Java source files with workspace status information:
```python theme={null}
load("@bazel_tools//tools/build_defs/build_info:bazel_java_build_info.bzl", "bazel_java_build_info")
bazel_java_build_info(
name = "build_info",
stamp = 1,
)
java_binary(
name = "my_app",
srcs = ["Main.java", ":build_info"],
main_class = "com.example.Main",
)
```
This will generate a Java source file containing the workspace status values
as string constants, which you can then use in your Java code:
```java theme={null}
// In your Java code
public class Main {
public static void main(String[] args) {
System.out.println("Build label: " + BuildInfo.BUILD_LABEL);
System.out.println("Build host: " + BuildInfo.BUILD_HOST);
System.out.println("Build user: " + BuildInfo.BUILD_USER);
}
}
```
#### `--[no]stamp`
This option, in conjunction with the `stamp` rule attribute, controls whether to
embed build information in binaries.
Stamping can be enabled or disabled explicitly on a per-rule basis using the
`stamp` attribute. Please refer to the Build Encyclopedia for details. When
a rule sets `stamp = -1` (the default for `*_binary` rules), this option
determines whether stamping is enabled.
Bazel never stamps binaries that are built for the exec configuration,
regardless of this option or the `stamp` attribute. For rules that set `stamp =
0` (the default for `*_test` rules), stamping is disabled regardless of
`--[no]stamp`. Specifying `--stamp` does not force targets to be rebuilt if
their dependencies have not changed.
Setting `--nostamp` is generally desireable for build performance, as it
reduces input volatility and maximizes build caching.
### Platform
Use these options to control the host and target platforms that configure how builds work, and to
control what execution platforms and toolchains are available to Bazel rules.
Please see background information on [Platforms](/extending/platforms) and [Toolchains](/extending/toolchains).
#### `--platforms=labels`
The labels of the platform rules describing the target platforms for the
current command.
#### `--host_platform=label`
The label of a platform rule that describes the host system.
#### `--extra_execution_platforms=labels`
The platforms that are available as execution platforms to run actions.
Platforms can be specified by exact target, or as a target pattern. These
platforms will be considered before those declared in MODULE.bazel files by
[register\_execution\_platforms()](/rules/lib/globals/module#register_execution_platforms).
This option accepts a comma-separated list of platforms in order of priority.
If the flag is passed multiple times, the most recent overrides.
#### `--extra_toolchains=labels`
The toolchain rules to be considered during toolchain resolution. Toolchains
can be specified by exact target, or as a target pattern. These toolchains will
be considered before those declared in MODULE.bazel files by
[register\_toolchains()](/rules/lib/globals/module#register_toolchains).
#### `--toolchain_resolution_debug=regex`
Print debug information while finding toolchains if the toolchain type matches
the regex. Multiple regexes can be separated by commas. The regex can be
negated by using a `-` at the beginning. This might help developers
of Bazel or Starlark rules with debugging failures due to missing toolchains.
### Miscellaneous
#### `--flag_alias=alias_name=target_path`
A convenience flag used to bind longer Starlark build settings to a shorter name. For more
details, see the
[Starlark Configurations](/extending/config#using-build-setting-aliases).
#### `--symlink_prefix=string`
Changes the prefix of the generated convenience symlinks. The
default value for the symlink prefix is `bazel-` which
will create the symlinks `bazel-bin`, `bazel-testlogs`, and
`bazel-genfiles`.
If the symbolic links cannot be created for any reason, a warning is
issued but the build is still considered a success. In particular,
this allows you to build in a read-only directory or one that you have no
permission to write into. Any paths printed in informational
messages at the conclusion of a build will only use the
symlink-relative short form if the symlinks point to the expected
location; in other words, you can rely on the correctness of those
paths, even if you cannot rely on the symlinks being created.
Some common values of this option:
* **Suppress symlink creation:**
`--symlink_prefix=/` will cause Bazel to not
create or update any symlinks, including the `bazel-out` and
`bazel-`
symlinks. Use this option to suppress symlink creation entirely.
* **Reduce clutter:**
`--symlink_prefix=.bazel/` will cause Bazel to create
symlinks called `bin` (etc) inside a hidden directory `.bazel`.
#### `--platform_suffix=string`
Adds a suffix to the configuration short name, which is used to determine the
output directory. Setting this option to different values puts the files into
different directories, for example to improve cache hit rates for builds that
otherwise clobber each others output files, or to keep the output files around
for comparisons.
#### `--default_visibility=(private|public)`
Temporary flag for testing bazel default visibility changes. Not intended for general use
but documented for completeness' sake.
#### `--starlark_cpu_profile=_file_`
This flag, whose value is the name of a file, causes Bazel to gather
statistics about CPU usage by all Starlark threads,
and write the profile, in [pprof](https://github.com/google/pprof) format,
to the named file.
Use this option to help identify Starlark functions that
make loading and analysis slow due to excessive computation. For example:
$bazel build --nobuild --starlark_cpu_profile=/tmp/pprof.gz my/project/...$ pprof /tmp/pprof.gz
(pprof) top
Type: CPU
Time: Feb 6, 2020 at 12:06pm (PST)
Duration: 5.26s, Total samples = 3.34s (63.55%)
Showing nodes accounting for 3.34s, 100% of 3.34s total
flat flat% sum% cum cum%
1.86s 55.69% 55.69% 1.86s 55.69% sort\_source\_files
1.02s 30.54% 86.23% 1.02s 30.54% expand\_all\_combinations
0.44s 13.17% 99.40% 0.44s 13.17% range
0.02s 0.6% 100% 3.34s 100% sorted
0 0% 100% 1.38s 41.32% my/project/main/BUILD
0 0% 100% 1.96s 58.68% my/project/library.bzl
0 0% 100% 3.34s 100% main
For different views of the same data, try the `pprof` commands `svg`,
`web`, and `list`.
## Using Bazel for releases
Bazel is used both by software engineers during the development
cycle, and by release engineers when preparing binaries for deployment
to production. This section provides a list of tips for release
engineers using Bazel.
### Significant options
When using Bazel for release builds, the same issues arise as for other scripts
that perform a build. For more details, see
[Call Bazel from scripts](/run/scripts). In particular, the following options
are strongly recommended:
* [`--bazelrc=/dev/null`](/run/bazelrc)
* [`--nokeep_state_after_build`](/reference/command-line-reference#common_options-flag--keep_state_after_build)
These options are also important:
* [`--package_path`](#package-path)
* [`--symlink_prefix`](#symlink-prefix):
for managing builds for multiple configurations,
it may be convenient to distinguish each build
with a distinct identifier, such as "64bit" vs. "32bit". This option
differentiates the `bazel-bin` (etc.) symlinks.
## Running tests
To build and run tests with bazel, type `bazel test` followed by
the name of the test targets.
By default, this command performs simultaneous build and test
activity, building all specified targets (including any non-test
targets specified on the command line) and testing
`*_test` and `test_suite` targets as soon as
their prerequisites are built, meaning that test execution is
interleaved with building. Doing so usually results in significant
speed gains.
### Options for `bazel test`
#### `--cache_test_results=(yes|no|auto)` (`-t`)
If this option is set to 'auto' (the default) then Bazel will only rerun a test if any of the
following conditions applies:
* Bazel detects changes in the test or its dependencies
* the test is marked as `external`
* multiple test runs were requested with `--runs_per_test`
* the test failed.
If 'no', all tests will be executed unconditionally.
If 'yes', the caching behavior will be the same as auto
except that it may cache test failures and test runs with
`--runs_per_test`.
Note: Test results are *always* saved in Bazel's output tree,
regardless of whether this option is enabled, so
you needn't have used `--cache_test_results` on the
prior run(s) of `bazel test` in order to get cache hits.
The option only affects whether Bazel will *use* previously
saved results, not whether it will save results of the current run.
Users who have enabled this option by default in
their `.bazelrc` file may find the
abbreviations `-t` (on) or `-t-` (off)
convenient for overriding the default on a particular run.
#### `--check_tests_up_to_date`
This option tells Bazel not to run the tests, but to merely check and report
the cached test results. If there are any tests which have not been
previously built and run, or whose tests results are out-of-date (for example, because
the source code or the build options have changed), then Bazel will report
an error message ("test result is not up-to-date"), will record the test's
status as "NO STATUS" (in red, if color output is enabled), and will return
a non-zero exit code.
This option also implies
[`--check_up_to_date`](#check-up-to-date) behavior.
This option may be useful for pre-submit checks.
#### `--test_verbose_timeout_warnings`
This option tells Bazel to explicitly warn the user if a test's timeout is
significantly longer than the test's actual execution time. While a test's
timeout should be set such that it is not flaky, a test that has a highly
over-generous timeout can hide real problems that crop up unexpectedly.
For instance, a test that normally executes in a minute or two should not have
a timeout of ETERNAL or LONG as these are much, much too generous.
This option is useful to help users decide on a good timeout value or
sanity check existing timeout values.
Note: Each test shard is allotted the timeout of the entire
`XX_test` target. Using this option does not affect a test's timeout
value, merely warns if Bazel thinks the timeout could be restricted further.
#### `--[no]test_keep_going`
By default, all tests are run to completion. If this flag is disabled,
however, the build is aborted on any non-passing test. Subsequent build steps
and test invocations are not run, and in-flight invocations are canceled.
Do not specify both `--notest_keep_going` and `--keep_going`.
#### `--flaky_test_attempts=attempts`
This option specifies the maximum number of times a test should be attempted
if it fails for any reason. A test that initially fails but eventually
succeeds is reported as `FLAKY` on the test summary. It is,
however, considered to be passed when it comes to identifying Bazel exit code
or total number of passed tests. Tests that fail all allowed attempts are
considered to be failed.
By default (when this option is not specified, or when it is set to
default), only a single attempt is allowed for regular tests, and
3 for test rules with the `flaky` attribute set. You can specify
an integer value to override the maximum limit of test attempts. Bazel allows
a maximum of 10 test attempts in order to prevent abuse of the system.
#### `--runs_per_test=[regex@]number`
This option specifies the number of times each test should be executed. All
test executions are treated as separate tests (fallback functionality
will apply to each of them independently).
The status of a target with failing runs depends on the value of the
`--runs_per_test_detects_flakes` flag:
* If absent, any failing run causes the entire test to fail.
* If present and two runs from the same shard return PASS and FAIL, the test
will receive a status of flaky (unless other failing runs cause it to
fail).
If a single number is specified, all tests will run that many times.
Alternatively, a regular expression may be specified using the syntax
regex\@number. This constrains the effect of `--runs_per_test` to targets
which match the regex (`--runs_per_test=^//pizza:.*@4` runs all tests
under `//pizza/` 4 times).
This form of `--runs_per_test` may be specified more than once.
#### `--[no]runs_per_test_detects_flakes`
If this option is specified (by default it is not), Bazel will detect flaky
test shards through `--runs_per_test`. If one or more runs for a single shard
fail and one or more runs for the same shard pass, the target will be
considered flaky with the flag. If unspecified, the target will report a
failing status.
#### `--test_summary=output_style`
Specifies how the test result summary should be displayed.
* `short` lists all tests that ran to completion, along with the name of
the file containing the test output if the test failed. This is the
default value.
* `short_uncached` like `short`, but omits tests whose results were cached.
* `terse` lists only failed and flaky tests.
* `detailed` lists all tests that ran to completion and prints each
individual test case (passed, skipped, and failed). The names of test
output files are omitted.
* `detailed_uncached` like `detailed`, but omits tests whose results were
cached.
* `testcase` prints a summary at test-case resolution without detailed
information about failed test cases.
* `none` does not print a test summary.
#### `--test_output=output_style`
Specifies how test output should be displayed:
* `summary` shows a summary of whether each test passed or
failed. Also shows the output log file name for failed tests. The summary
will be printed at the end of the build (during the build, one would see
just simple progress messages when tests start, pass or fail).
This is the default behavior.
* `errors` sends combined stdout/stderr output from failed tests
only into the stdout immediately after test is completed, ensuring that
test output from simultaneous tests is not interleaved with each other.
Prints a summary at the build as per summary output above.
* `all` is similar to `errors` but prints output for
all tests, including those which passed.
* `streamed` streams stdout/stderr output from each test in
real-time.
#### `--java_debug`
This option causes the Java virtual machine of a java test to wait for a connection from a
JDWP-compliant debugger before starting the test. This option implies `--test_output=streamed`.
#### `--[no]verbose_test_summary`
By default this option is enabled, causing test times and other additional
information (such as test attempts) to be printed to the test summary. If
`--noverbose_test_summary` is specified, test summary will
include only test name, test status and cached test indicator and will
be formatted to stay within 80 characters when possible.
#### `--test_tmpdir=path`
Specifies temporary directory for tests. Each test will be executed in a
separate subdirectory inside this directory. The directory will be cleaned at
the beginning of each `bazel test` command.
By default, Bazel will place this directory under the Bazel output base directory.
Note: This is a directory for running tests, not storing test results
(those are always stored under the `bazel-out` directory).
#### `--test_timeout=seconds` OR `--test_timeout=seconds,seconds,seconds,seconds`
Overrides the timeout value for all tests by using specified number of
seconds as a new timeout value. If only one value is provided, then it will
be used for all test timeout categories.
Alternatively, four comma-separated values may be provided, specifying
individual timeouts for short, moderate, long and eternal tests (in that
order).
In either form, zero or a negative value for any of the test sizes will
be substituted by the default timeout for the given timeout categories as
defined by the page [Writing Tests](/reference/test-encyclopedia).
By default, Bazel will use these timeouts for all tests by
inferring the timeout limit from the test's size whether the size is
implicitly or explicitly set.
Tests which explicitly state their timeout category as distinct from their
size will receive the same value as if that timeout had been implicitly set by
the size tag. So a test of size 'small' which declares a 'long' timeout will
have the same effective timeout that a 'large' tests has with no explicit
timeout.
#### `--test_arg=arg`
Passes command-line options/flags/arguments to each test process. This
option can be used multiple times to pass several arguments. For example,
`--test_arg=--logtostderr --test_arg=--v=3`.
Note that, unlike the `bazel run` command, you can't pass test arguments
directly as in `bazel test -- target --logtostderr --v=3`. That's because
extraneous arguments passed to `bazel test` are interpreted as additional test
targets. That is, `--logtostderr` and `--v=3` would each be interpreted as a
test target. This ambiguity doesn't exist for a `bazel run` command, which only
accepts one target.
`--test_arg` can be passed to a `bazel run` command, but it's ignored unless the
target being run is a test target. (As with any other flag, if it's passed in a
`bazel run` command after a `--` token, it's not processed by Bazel but
forwarded verbatim to the executed target.)
#### `--test_env=variable=_value_` OR `--test_env=variable`
Specifies additional variables that must be injected into the test
environment for each test. If value is not specified it will be
inherited from the shell environment used to start the `bazel test`
command.
The environment can be accessed from within a test by using
`System.getenv("var")` (Java), `getenv("var")` (C or C++),
#### `--run_under=command-prefix`
This specifies a prefix that the test runner will insert in front
of the test command before running it. The
command-prefix is split into words using Bourne shell
tokenization rules, and then the list of words is prepended to the
command that will be executed.
If the first word is a fully-qualified label (starts with
`//`) it is built. Then the label is substituted by the
corresponding executable location that is prepended to the command
that will be executed along with the other words.
Some caveats apply:
* The PATH used for running tests may be different than the PATH in your environment,
so you may need to use an **absolute path** for the `--run_under`
command (the first word in command-prefix).
* **`stdin` is not connected**, so `--run_under`
can't be used for interactive commands.
Examples:
#### Test selection
As documented under [Output selection options](#output-selection),
you can filter tests by [size](#test-size-filters),
[timeout](#test-timeout-filters),
[tag](#test-tag-filters), or
[language](#test-lang-filters). A convenience
[general name filter](#test-filter) can forward particular
filter args to the test runner.
#### Other options for `bazel test`
The syntax and the remaining options are exactly like
[`bazel build`](/run/build).
## Running executables
The `bazel run` command is similar to `bazel build`, except
it is used to build *and run* a single target. Here is a typical session
(`//java/myapp:myapp` says hello and prints out its args):
Note: `--` is needed so that Bazel
does not interpret `--arg1` and `--arg2` as
Bazel options, but rather as part of the command line for running the binary.
Additionally, Bazel will avoid logging these arguments to the console in case
they contain sensitive information.
`bazel run` is similar, but not identical, to directly invoking
the binary built by Bazel and its behavior is different depending on whether the
binary to be invoked is a test or not.
When the binary is not a test, the current working directory will be the
runfiles tree of the binary.
When the binary is a test, the current working directory will be the exec root
and a good-faith attempt is made to replicate the environment tests are usually
run in. The emulation is not perfect, though, and tests that have multiple
shards cannot be run this way (the
`--test_sharding_strategy=disabled` command line option can be used
to work around this)
The following extra environment variables are also available to the binary:
* `BUILD_WORKSPACE_DIRECTORY`: the root of the workspace where the
build was run.
* `BUILD_WORKING_DIRECTORY`: the current working directory where
Bazel was run from.
* `BUILD_ID`: the build ID of the `bazel run` invocation. This is usually
unique, except if Bazel was run with `--script_path` and the resulting
script is re-used.
* `BUILD_EXECROOT`: the execution root of the `bazel run` invocation.
These can be used, for example, to interpret file names on the command line in
a user-friendly way.
### Options for `bazel run`
#### `--run_under=command-prefix`
This has the same effect as the `--run_under` option for
`bazel test` ([see above](#test-run-under)),
except that it applies to the command being run by `bazel
run` rather than to the tests being run by `bazel test`
and cannot run under label.
#### Filtering logging outputs from Bazel
When invoking a binary with `bazel run`, Bazel prints logging output from Bazel
itself and the binary under invocation. To make the logs less noisy, you can
suppress the outputs from Bazel itself with the `--ui_event_filters` and
`--noshow_progress` flags.
For example:
`bazel run --ui_event_filters=-info,-stdout,-stderr --noshow_progress //java/myapp:myapp`
### Executing tests
`bazel run` can also execute test binaries, which has the effect of
running the test in a close approximation of the environment described at
[Writing Tests](/reference/test-encyclopedia). Note that none of the
`--test_*` arguments have an effect when running a test in this manner except
`--test_arg` .
## Cleaning build outputs
### The `clean` command
Bazel has a `clean` command, analogous to that of Make.
It deletes the output directories for all build configurations performed
by this Bazel instance, or the entire working tree created by this
Bazel instance, and resets internal caches. If executed without any
command-line options, then the output directory for all configurations
will be cleaned.
Recall that each Bazel instance is associated with a single workspace, thus the
`clean` command will delete all outputs from all builds you've done
with that Bazel instance in that workspace.
To completely remove the entire working tree created by a Bazel
instance, you can specify the `--expunge` option. When
executed with `--expunge`, the clean command simply
removes the entire output base tree which, in addition to the build
output, contains all temp files created by Bazel. It also
stops the Bazel server after the clean, equivalent to the [`shutdown`](#shutdown) command. For example, to
clean up all disk and memory traces of a Bazel instance, you could
specify:
% bazel clean --expunge
Alternatively, you can expunge in the background by using
`--expunge_async`. It is safe to invoke a Bazel command
in the same client while the asynchronous expunge continues to run.
Note: This may introduce IO contention.
The `clean` command is provided primarily as a means of
reclaiming disk space for workspaces that are no longer needed.
Bazel's incremental rebuilds may not be
perfect so `clean` can be used to recover a consistent
state when problems arise.
Bazel's design is such that these problems are fixable and
these bugs are a high priority to be fixed. If you
ever find an incorrect incremental build, file a bug report, and report bugs in the tools
rather than using `clean`.
## Querying the dependency graph
Bazel includes a query language for asking questions about the
dependency graph used during the build. The query language is used
by two commands: query and cquery. The major difference between the
two commands is that query runs after the [loading phase](/run/build#loading)
and cquery runs after the [analysis phase](/run/build#analysis). These tools are an
invaluable aid to many software engineering tasks.
The query language is based on the idea of
algebraic operations over graphs; it is documented in detail in
[Bazel Query Reference](/query/language).
Please refer to that document for reference, for
examples, and for query-specific command-line options.
The query tool accepts several command-line
option. `--output` selects the output format.
`--[no]keep_going` (disabled by default) causes the query
tool to continue to make progress upon errors; this behavior may be
disabled if an incomplete result is not acceptable in case of errors.
The `--[no]tool_deps` option,
enabled by default, causes dependencies in non-target configurations to be included in the
dependency graph over which the query operates.
The `--[no]implicit_deps` option, enabled by default, causes
implicit dependencies to be included in the dependency graph over which the query operates. An
implicit dependency is one that is not explicitly specified in the BUILD file
but added by bazel.
Example: "Show the locations of the definitions (in BUILD files) of
all genrules required to build all the tests in the PEBL tree."
## Querying the action graph
Caution: The aquery command is still experimental and its API will change.
The `aquery` command allows you to query for actions in your build graph.
It operates on the post-analysis configured target graph and exposes
information about actions, artifacts and their relationships.
The tool accepts several command-line options.
`--output` selects the output format. The default output format
(`text`) is human-readable, use `proto` or `textproto` for
machine-readable format.
Notably, the aquery command runs on top of a regular Bazel build and inherits
the set of options available during a build.
It supports the same set of functions that is also available to traditional
`query` but `siblings`, `buildfiles` and
`tests`.
For more details, see [Action Graph Query](/query/aquery).
## Miscellaneous commands and options
### `help`
The `help` command provides on-line help. By default, it
shows a summary of available commands and help topics, as shown in
[Building with Bazel](/run/build#quickstart).
Specifying an argument displays detailed help for a particular
topic. Most topics are Bazel commands, such as `build`
or `query`, but there are some additional help topics
that do not correspond to commands.
#### `--[no]long` (`-l`)
By default, `bazel help [topic]` prints only a
summary of the relevant options for a topic. If
the `--long` option is specified, the type, default value
and full description of each option is also printed.
### `shutdown`
Bazel server processes may be stopped by using the `shutdown`
command. This command causes the Bazel server to exit as soon as it
becomes idle (for example, after the completion of any builds or other
commands that are currently in progress). For more details, see
[Client/server implementation](/run/client-server).
Bazel servers stop themselves after an idle timeout, so this command
is rarely necessary; however, it can be useful in scripts when it is
known that no further builds will occur in a given workspace.
`shutdown` accepts one
option, `--iff_heap_size_greater_than _n_`, which
requires an integer argument (in MB). If specified, this makes the shutdown
conditional on the amount of memory already consumed. This is
useful for scripts that initiate a lot of builds, as any memory
leaks in the Bazel server could cause it to crash spuriously on
occasion; performing a conditional restart preempts this condition.
### `info`
The `info` command prints various values associated with
the Bazel server instance, or with a specific build configuration.
(These may be used by scripts that drive a build.)
The `info` command also permits a single (optional)
argument, which is the name of one of the keys in the list below.
In this case, `bazel info key` will print only
the value for that one key. (This is especially convenient when
scripting Bazel, as it avoids the need to pipe the result
through `sed -ne /key:/s/key://p`:
#### Configuration-independent data
* `release`: the release label for this Bazel
instance, or "development version" if this is not a released
binary.
* `workspace` the absolute path to the base workspace
directory.
* `install_base`: the absolute path to the installation
directory used by this Bazel instance for the current user. Bazel
installs its internally required executables below this directory.
* `output_base`: the absolute path to the base output
directory used by this Bazel instance for the current user and
workspace combination. Bazel puts all of its scratch and build
output below this directory.
* `execution_root`: the absolute path to the execution
root directory under output\_base. This directory is the root for all files
accessible to commands executed during the build, and is the working
directory for those commands. If the workspace directory is writable, a
symlink named `bazel-`
is placed there pointing to this directory.
* `output_path`: the absolute path to the output
directory beneath the execution root used for all files actually
generated as a result of build commands. If the workspace directory is
writable, a symlink named `bazel-out` is placed there pointing
to this directory.
* `server_pid`: the process ID of the Bazel server
process.
* `server_log`: the absolute path to the Bazel server's debug log file.
This file contains debugging information for all commands over the lifetime of the
Bazel server, and is intended for human consumption by Bazel developers and power users.
* `command_log`: the absolute path to the command log file;
this contains the interleaved stdout and stderr streams of the most recent
Bazel command. Note that running `bazel info` will overwrite the
contents of this file, since it then becomes the most recent Bazel command.
However, the location of the command log file will not change unless you
change the setting of the `--output_base` or
`--output_user_root` options.
* `used-heap-size`,
`committed-heap-size`,
`max-heap-size`: reports various JVM heap size
parameters. Respectively: memory currently used, memory currently
guaranteed to be available to the JVM from the system, maximum
possible allocation.
* `gc-count`, `gc-time`: The cumulative count of
garbage collections since the start of this Bazel server and the time spent
to perform them. Note that these values are not reset at the start of every
build.
* `package_path`: A colon-separated list of paths which would be
searched for packages by bazel. Has the same format as the
`--package_path` build command line argument.
Example: the process ID of the Bazel server.
% bazel info server\_pid
1285
#### Configuration-specific data
These data may be affected by the configuration options passed
to `bazel info`, for
example `--cpu`, `--compilation_mode`,
etc. The `info` command accepts all
the options that control dependency
analysis, since some of these determine the location of the
output directory of a build, the choice of compiler, etc.
* `bazel-bin`, `bazel-testlogs`,
`bazel-genfiles`: reports the absolute path to
the `bazel-*` directories in which programs generated by the
build are located. This is usually, though not always, the same as
the `bazel-*` symlinks created in the base workspace directory after a
successful build. However, if the workspace directory is read-only,
no `bazel-*` symlinks can be created. Scripts that use
the value reported by `bazel info`, instead of assuming the
existence of the symlink, will be more robust.
* The complete
["Make" environment](/reference/be/make-variables). If the `--show_make_env` flag is
specified, all variables in the current configuration's "Make" environment
are also displayed (such as `CC`, `GLIBC_VERSION`, etc).
These are the variables accessed using the `$(CC)`
or `varref("CC")` syntax inside BUILD files.
Example: the C++ compiler for the current configuration.
This is the `$(CC)` variable in the "Make" environment,
so the `--show_make_env` flag is needed.
% bazel info --show\_make\_env -c opt COMPILATION\_MODE
opt
Example: the `bazel-bin` output directory for the current
configuration. This is guaranteed to be correct even in cases where
the `bazel-bin` symlink cannot be created for some reason
(such as if you are building from a read-only directory).
% bazel info --cpu=piii bazel-bin
/var/tmp/\_bazel\_johndoe/fbd0e8a34f61ce5d491e3da69d959fe6/execroot/io\_bazel/bazel-out/piii-opt/bin
% bazel info --cpu=k8 bazel-bin
/var/tmp/\_bazel\_johndoe/fbd0e8a34f61ce5d491e3da69d959fe6/execroot/io\_bazel/bazel-out/k8-opt/bin
### `version` and `--version`
The version command prints version details about the built Bazel
binary, including the changelist at which it was built and the date.
These are particularly useful in determining if you have the latest
Bazel, or if you are reporting bugs. Some of the interesting values
are:
* `changelist`: the changelist at which this version of
Bazel was released.
* `label`: the release label for this Bazel
instance, or "development version" if this is not a released
binary. Very useful when reporting bugs.
`bazel --version`, with no other args, will emit the same output as
`bazel version --gnu_format`, except without the side-effect of potentially starting
a Bazel server or unpacking the server archive. `bazel --version` can be run from
anywhere - it does not require a workspace directory.
### `mobile-install`
The `mobile-install` command installs apps to mobile devices.
Currently only Android devices running ART are supported.
See [bazel mobile-install](/docs/mobile-install) for more information.
Note: This command does not install the same thing that
`bazel build` produces: Bazel tweaks the app so that it can be
built, installed and re-installed quickly. This should, however, be mostly
transparent to the app.
The following options are supported:
#### `--incremental`
If set, Bazel tries to install the app incrementally, that is, only those
parts that have changed since the last build. This cannot update resources
referenced from `AndroidManifest.xml`, native code or Java
resources (such as those referenced by `Class.getResource()`). If these
things change, this option must be omitted. Contrary to the spirit of Bazel
and due to limitations of the Android platform, it is the
**responsibility of the user** to know when this command is good enough and
when a full install is needed.
If you are using a device with Marshmallow or later, consider the
[`--split_apks`](#split-apks) flag.
#### `--split_apks`
Whether to use split apks to install and update the application on the device.
Works only with devices with Marshmallow or later. Note that the
[`--incremental`](#incremental) flag
is not necessary when using `--split_apks`.
#### `--start_app`
Starts the app in a clean state after installing. Equivalent to `--start=COLD`.
#### `--debug_app`
Waits for debugger to be attached before starting the app in a clean state after installing.
Equivalent to `--start=DEBUG`.
#### `--start=_start_type_`
How the app should be started after installing it. Supported \_start\_type\_s are:
* `NO` Does not start the app. This is the default.
* `COLD` Starts the app from a clean state after install.
* `WARM` Preserves and restores the application state on incremental installs.
* `DEBUG` Waits for the debugger before starting the app in a clean state after
install.
Note: If more than one of `--start=_start_type_`, `--start_app` or
`--debug_app` is set, the last value is used.
#### `--adb=path`
Indicates the `adb` binary to be used.
The default is to use the adb in the Android SDK specified by
[`--android_sdk`](#android-sdk).
#### `--adb_arg=serial`
Extra arguments to `adb`. These come before the subcommand in the
command line and are typically used to specify which device to install to.
For example, to select the Android device or emulator to use:
#### `--incremental_install_verbosity=number`
The verbosity for incremental install. Set to 1 for debug logging to be
printed to the console.
### `dump`
The `dump` command prints to stdout a dump of the
internal state of the Bazel server. This command is intended
primarily for use by Bazel developers, so the output of this command
is not specified, and is subject to change.
By default, command will just print help message outlining possible
options to dump specific areas of the Bazel state. In order to dump
internal state, at least one of the options must be specified.
Following options are supported:
* `--action_cache` dumps action cache content.
* `--packages` dumps package cache content.
* `--skyframe` dumps state of internal Bazel dependency graph.
* `--rules` dumps rule summary for each rule and aspect class,
including counts and action counts. This includes both native and Starlark rules.
If memory tracking is enabled, then the rules' memory consumption is also printed.
* `--skylark_memory` dumps a
[pprof](https://github.com/google/pprof) compatible .gz file to the specified path.
You must enable memory tracking for this to work.
#### Memory tracking
Some `dump` commands require memory tracking. To turn this on, you have to pass
startup flags to Bazel:
* `--host_jvm_args=-javaagent:$BAZEL/third_party/allocation_instrumenter/java-allocation-instrumenter-3.3.4.jar`
* `--host_jvm_args=-DRULE_MEMORY_TRACKER=1`
The java-agent is checked into Bazel at
`third_party/allocation_instrumenter/java-allocation-instrumenter-3.3.4.jar`, so
make sure you adjust `$BAZEL` for where you keep your Bazel repository.
Do not forget to keep passing these options to Bazel for every command or the server will
restart.
Example:
### `canonicalize-flags`
The [`canonicalize-flags`](/reference/command-line-reference#canonicalize-flags-options)
command, which takes a list of options for a Bazel command and returns a list of
options that has the same effect. The new list of options is canonical. For example,
two lists of options with the same effect are canonicalized to the same new list.
The `--for_command` option can be used to select between different
commands. At this time, only `build` and `test` are
supported. Options that the given command does not support cause an error.
Note: A small number of options cannot be reordered, because Bazel cannot
ensure that the effect is identical. Also note that this command
*does not* expand flags from `--config`.
As an example:
### Startup options
The options described in this section affect the startup of the Java
virtual machine used by Bazel server process, and they apply to all
subsequent commands handled by that server. If there is an already
running Bazel server and the startup options do not match, it will
be restarted.
All of the options described in this section must be specified using the
`--key=value` or `--key value`
syntax. Also, these options must appear *before* the name of the Bazel
command. Use `startup --key=value` to list these in a `.bazelrc` file.
#### `--output_base=dir`
This option requires a path argument, which must specify a
writable directory. Bazel will use this location to write all its
output. The output base is also the key by which the client locates
the Bazel server. By changing the output base, you change the server
which will handle the command.
By default, the output base is derived from the user's login name,
and the name of the workspace directory (actually, its MD5 digest),
so a typical value looks like:
`/var/tmp/google/_bazel_johndoe/d41d8cd98f00b204e9800998ecf8427e`.
Note: The client uses the output base to find the Bazel server
instance, so if you specify a different output base in a Bazel
command, a different server will be found (or started) to handle the
request. It's possible to perform two concurrent builds in the same
workspace directory by varying the output base.
For example:
In this command, the two Bazel commands run concurrently (because of
the shell `&` operator), each using a different Bazel
server instance (because of the different output bases).
In contrast, if the default output base was used in both commands,
then both requests would be sent to the same server, which would
handle them sequentially: building `//foo` first, followed
by an incremental build of `//bar`.
Note: We recommend you do not use an NFS or similar networked file system for the root
directory, as the higher access latency will cause noticeably slower builds.
#### `--output_user_root=dir`
Points to the root directory where output and install bases are created. The directory
must either not exist or be owned by the calling user. In the past,
this was allowed to point to a directory shared among various users
but it's not allowed any longer. This may be allowed once
[issue #11100](https://github.com/bazelbuild/bazel/issues/11100) is addressed.
If the `--output_base` option is specified, it overrides
using `--output_user_root` to calculate the output base.
The install base location is calculated based on
`--output_user_root`, plus the MD5 identity of the Bazel embedded
binaries.
You can use the `--output_user_root` option to choose an
alternate base location for all of Bazel's output (install base and output
base) if there is a better location in your filesystem layout.
Note: We recommend you do not use an NFS or similar networked file system for the root
directory, as the higher access latency will cause noticeably slower builds.
#### `--server_javabase=dir`
Specifies the Java virtual machine in which *Bazel itself* runs. The value must be a path to
the directory containing a JDK or JRE. It should not be a label.
This option should appear before any Bazel command, for example:
This flag does *not* affect the JVMs used by Bazel subprocesses such as applications, tests,
tools, and so on. Use build options [--javabase](#javabase) or
[--host\_javabase](#host-javabase) instead.
This flag was previously named `--host_javabase` (sometimes referred to as the
'left-hand side' `--host_javabase`), but was renamed to avoid confusion with the
build flag [--host\_javabase](#host-javabase) (sometimes referred to as the
'right-hand side' `--host_javabase`).
#### `--host_jvm_args=string`
Specifies a startup option to be passed to the Java virtual machine in which *Bazel itself*
runs. This can be used to set the stack size, for example:
% bazel --host\_jvm\_args="-Xss256K" build //foo
This option can be used multiple times with individual arguments. Note that
setting this flag should rarely be needed. You can also pass a space-separated list of strings,
each of which will be interpreted as a separate JVM argument, but this feature will soon be
deprecated.
That this does *not* affect any JVMs used by
subprocesses of Bazel: applications, tests, tools, and so on. To pass
JVM options to executable Java programs, whether run by `bazel
run` or on the command-line, you should use
the `--jvm_flags` argument which
all `java_binary` and `java_test` programs
support. Alternatively for tests, use `bazel test --test_arg=--jvm_flags=foo ...`.
#### `--host_jvm_debug`
This option causes the Java virtual machine to wait for a connection
from a JDWP-compliant debugger before
calling the main method of *Bazel itself*. This is primarily
intended for use by Bazel developers.
Note: This does *not* affect any JVMs used by subprocesses of Bazel:
applications, tests, tools, etc.
#### `--autodetect_server_javabase`
This option causes Bazel to automatically search for an installed JDK on startup,
and to fall back to the installed JRE if the embedded JRE isn't available.
`--explicit_server_javabase` can be used to pick an explicit JRE to
run Bazel with.
#### `--batch`
Batch mode causes Bazel to not use the
[standard client/server mode](/run/client-server), but instead runs a bazel
java process for a single command, which has been used for more predictable
semantics with respect to signal handling, job control, and environment
variable inheritance, and is necessary for running bazel in a chroot jail.
Batch mode retains proper queueing semantics within the same output\_base.
That is, simultaneous invocations will be processed in order, without overlap.
If a batch mode Bazel is run on a client with a running server, it first
kills the server before processing the command.
Bazel will run slower in batch mode, or with the alternatives described above.
This is because, among other things, the build file cache is memory-resident, so it is not
preserved between sequential batch invocations.
Therefore, using batch mode often makes more sense in cases where performance
is less critical, such as continuous builds.
Warning: `--batch` is sufficiently slower than standard
client/server mode. Additionally it might not support all of the features and optimizations which
are made possible by a persistent Bazel server. If you're using `--batch`
for the purpose of build isolation, you should use the command option
`--nokeep_state_after_build`, which guarantees that no incremental
in-memory state is kept between builds. In order to restart the Bazel server and JVM after a
build, please explicitly do so using the "shutdown" command.
#### `--max_idle_secs=n`
This option specifies how long, in seconds, the Bazel server process
should wait after the last client request, before it exits. The
default value is 10800 (3 hours). `--max_idle_secs=0` will cause the
Bazel server process to persist indefinitely.
Note: this flag is only read if Bazel needs
to start a new server. Changing this option will not cause the server to restart.
Note: system sleep time where a build is not running is counted as idle time.
This option may be used by scripts that invoke Bazel to ensure that
they do not leave Bazel server processes on a user's machine when they
would not be running otherwise.
For example, a presubmit script might wish to
invoke `bazel query` to ensure that a user's pending
change does not introduce unwanted dependencies. However, if the
user has not done a recent build in that workspace, it would be
undesirable for the presubmit script to start a Bazel server just
for it to remain idle for the rest of the day.
By specifying a small value of `--max_idle_secs` in the
query request, the script can ensure that *if* it caused a new
server to start, that server will exit promptly, but if instead
there was already a server running, that server will continue to run
until it has been idle for the usual time. Of course, the existing
server's idle timer will be reset.
#### `--[no]shutdown_on_low_sys_mem`
If enabled and `--max_idle_secs` is set to a positive duration, shut down an idle
build server when available system memory falls below critical thresholds.
Supported on Linux and macOS (no-op on Windows).
To avoid interrupting workflows or thrashing during active development, the server
only checks memory after it has been continuously idle for at least **5 minutes**
(any incoming command resets this idle window). While idle past 5 minutes, it checks
memory every 5 seconds:
* **Linux:** The server exits if available RAM (from `/proc/meminfo`) drops below
**both** 1 GiB and 5% of total system RAM.
* **macOS:** The server exits if the kernel signals a memory pressure level of
`WARNING` or `CRITICAL` via `dispatch_source_memorypressure`.
This flag is especially useful on multi-project developer workstations where multiple
idle Bazel servers across different repositories or output bases can cause system-wide
memory pressure. You can enable it globally in your user configuration file:
```ini theme={null}
# ~/.bazelrc
startup --shutdown_on_low_sys_mem
```
#### `--[no]block_for_lock`
If enabled, Bazel will wait for other Bazel commands holding the
server lock to complete before progressing. If disabled, Bazel will
exit in error if it cannot immediately acquire the lock and
proceed.
Developers might use this in presubmit checks to avoid long waits caused
by another Bazel command in the same client.
#### `--io_nice_level=n`
Sets a level from 0-7 for best-effort IO scheduling. 0 is highest priority,
7 is lowest. The anticipatory scheduler may only honor up to priority 4.
Negative values are ignored.
#### `--batch_cpu_scheduling`
Use `batch` CPU scheduling for Bazel. This policy is useful for
workloads that are non-interactive, but do not want to lower their nice value.
See 'man 2 sched\_setscheduler'. This policy may provide for better system
interactivity at the expense of Bazel throughput.
### Miscellaneous options
#### `--[no]announce_rc`
Controls whether Bazel announces startup options and command options read from
the bazelrc files when starting up.
#### `--color (yes|no|auto)`
This option determines whether Bazel will use colors to highlight
its output on the screen.
If this option is set to `yes`, color output is enabled.
If this option is set to `auto`, Bazel will use color output only if
the output is being sent to a terminal and the TERM environment variable
is set to a value other than `dumb`, `emacs`, or `xterm-mono`.
If this option is set to `no`, color output is disabled,
regardless of whether the output is going to a terminal and regardless
of the setting of the TERM environment variable.
#### `--config=name`
Selects additional config section from
[the rc files](/run/bazelrc#bazelrc-file-locations); for the current `command`,
it also pulls in the options from `command:name` if such a section exists. Can be
specified multiple times to add flags from several config sections. Expansions can refer to other
definitions (for example, expansions can be chained).
#### `--curses (yes|no|auto)`
This option determines whether Bazel will use cursor controls
in its screen output. This results in less scrolling data, and a more
compact, easy-to-read stream of output from Bazel. This works well with
`--color`.
If this option is set to `yes`, use of cursor controls is enabled.
If this option is set to `no`, use of cursor controls is disabled.
If this option is set to `auto`, use of cursor controls will be
enabled under the same conditions as for `--color=auto`.
#### `--[no]show_timestamps`
If specified, a timestamp is added to each message generated by
Bazel specifying the time at which the message was output.
# Installing / Updating Bazel using Bazelisk
Source: https://bazel.build/install/bazelisk
## Installing Bazel
[Bazelisk](https://github.com/bazelbuild/bazelisk) is the
recommended way to install Bazel on Ubuntu, Windows, and macOS. It automatically
downloads and installs the appropriate version of Bazel. Use Bazelisk if you
need to switch between different versions of Bazel depending on the current
working directory, or to always keep Bazel updated to the latest release.
For more details, see
[the official README](https://github.com/bazelbuild/bazelisk/blob/master/README.md).
## Updating Bazel
Bazel has a [backward compatibility policy](/release/backward-compatibility)
(see [guidance for rolling out incompatible changes](/contribute/breaking-changes) if you
are the author of one). That page summarizes best practices on how to test and
migrate your project with upcoming incompatible changes and how to provide
feedback to the incompatible change authors.
### Managing Bazel versions with Bazelisk
[Bazelisk](https://github.com/bazelbuild/bazelisk) helps you manage
Bazel versions.
Bazelisk can:
* Auto-update Bazel to the latest LTS or rolling release.
* Build the project with a Bazel version specified in the .bazelversion
file. Check in that file into your version control to ensure reproducibility
of your builds.
* Help migrate your project for incompatible changes (see above)
* Easily try release candidates
### Recommended migration process
Within minor updates to any LTS release, any
project can be prepared for the next release without breaking
compatibility with the current release. However, there may be
backward-incompatible changes between major LTS versions.
Follow this process to migrate from one major version to another:
1. Read the release notes to get advice on how to migrate to the next version.
2. Major incompatible changes should have an associated `--incompatible_*` flag
and a corresponding GitHub issue:
* Migration guidance is available in the associated GitHub issue.
* Tooling is available for some of incompatible changes migration. For
example, [buildifier](https://github.com/bazelbuild/buildtools/releases).
* Report migration problems by commenting on the associated GitHub issue.
After migration, you can continue to build your projects without worrying about
backward-compatibility until the next major release.
# Compiling Bazel from Source
Source: https://bazel.build/install/compile-source
This page describes how to install Bazel from source and provides
troubleshooting tips for common issues.
To build Bazel from source, you can do one of the following:
* Build it [using an existing Bazel binary](#build-bazel-using-bazel)
* Build it [without an existing Bazel binary](#bootstrap-bazel) which is known
as *bootstrapping*.
## Build Bazel using Bazel
### Summary
1. Get the latest Bazel release from the
[GitHub release page](https://github.com/bazelbuild/bazel/releases) or with
[Bazelisk](https://github.com/bazelbuild/bazelisk).
2. [Download Bazel's sources from GitHub](https://github.com/bazelbuild/bazel/archive/master.zip)
and extract somewhere.
Alternatively you can git clone the source tree from [https://github.com/bazelbuild/bazel](https://github.com/bazelbuild/bazel)
3. Install the same prerequisites as for bootstrapping (see
[for Unix-like systems](#bootstrap-unix-prereq) or
[for Windows](#bootstrap-windows-prereq))
4. Build a development build of Bazel using Bazel:
`bazel build //src:bazel-dev` (or `bazel build //src:bazel-dev.exe` on
Windows).
**Note:** Many rulesets rely on the Bazel version for feature detection.
For this to work correctly, the version must be embedded in the binary.
Build `bazel-dev` with:
`bazel build --stamp --embed_label="X.Y.Z" //src:bazel-dev`
where `X.Y.Z` is the Bazel version being built (for example, `8.6.0`).
5. The resulting binary is at `bazel-bin/src/bazel-dev`
(or `bazel-bin\src\bazel-dev.exe` on Windows). You can copy it wherever you
like and use immediately without further installation.
Detailed instructions follow below.
### Step 1: Get the latest Bazel release
**Goal**: Install or download a release version of Bazel. Make sure you can run
it by typing `bazel` in a terminal.
**Reason**: To build Bazel from a GitHub source tree, you need a pre-existing
Bazel binary. You can install one from a package manager or download one from
GitHub. See [Installing Bazel](/install). (Or you can [build from scratch (bootstrap)](#bootstrap-bazel).)
**Troubleshooting**:
* If you cannot run Bazel by typing `bazel` in a terminal:
* Maybe your Bazel binary's directory is not on the PATH.
This is not a big problem. Instead of typing `bazel`, you will need to
type the full path.
* Maybe the Bazel binary itself is not called `bazel` (on Unixes) or
`bazel.exe` (on Windows).
This is not a big problem. You can either rename the binary, or type the
binary's name instead of `bazel`.
* Maybe the binary is not executable (on Unixes).
You must make the binary executable by running `chmod +x /path/to/bazel`.
### Step 2: Download Bazel's sources from GitHub
If you are familiar with Git, then just git clone [https://github.com/bazelbuild/bazel](https://github.com/bazelbuild/bazel)
Otherwise:
1. Download the
[latest sources as a zip file](https://github.com/bazelbuild/bazel/archive/master.zip).
2. Extract the contents somewhere.
For example create a `bazel-src` directory under your home directory and
extract there.
### Step 3: Install prerequisites
Install the same prerequisites as for bootstrapping (see below) -- JDK, C++
compiler, MSYS2 (if you are building on Windows), etc.
### Step 4a: Build Bazel on Ubuntu Linux, macOS, and other Unix-like systems
For instructions for Windows, see [Build Bazel on Windows](#build-bazel-on-windows).
**Goal**: Run Bazel to build a custom Bazel binary (`bazel-bin/src/bazel-dev`).
**Instructions**:
1. Start a Bash terminal
2. `cd` into the directory where you extracted (or cloned) Bazel's sources.
For example if you extracted the sources under your home directory, run:
cd \~/bazel-src
3. Build Bazel from source:
bazel build //src:bazel-dev
Alternatively you can run `bazel build //src:bazel --compilation_mode=opt`
to yield a smaller binary but it's slower to build.
You can build with `--stamp --embed_label=X.Y.Z` flag to embed a Bazel
version for the binary so that `bazel --version` outputs the given version.
4. The output will be at `bazel-bin/src/bazel-dev` (or `bazel-bin/src/bazel`).
### Step 4b: Build Bazel on Windows
For instructions for Unix-like systems, see
[Ubuntu Linux, macOS, and other Unix-like systems](#build-bazel-on-unixes).
**Goal**: Run Bazel to build a custom Bazel binary
(`bazel-bin\src\bazel-dev.exe`).
**Instructions**:
1. Start Command Prompt (Start Menu > Run > "cmd.exe")
2. `cd` into the directory where you extracted (or cloned) Bazel's sources.
For example if you extracted the sources under your home directory, run:
cd %USERPROFILE%\bazel-src
3. Build Bazel from source:
bazel build //src:bazel-dev.exe
Alternatively you can run `bazel build //src:bazel.exe --compilation_mode=opt` to yield a smaller binary but it's slower to build.
You can build with `--stamp --embed_label=X.Y.Z` flag to embed a Bazel
version for the binary so that `bazel --version` outputs the given version.
4. The output will be at `bazel-bin\src\bazel-dev.exe` (or
`bazel-bin\src\bazel.exe`).
### Step 5: Install the built binary
Actually, there's nothing to install.
The output of the previous step is a self-contained Bazel binary. You can copy
it to any directory and use immediately. (It's useful if that directory is on
your PATH so that you can run "bazel" everywhere.)
***
## Build Bazel from scratch (bootstrapping)
You can also build Bazel from scratch, without using an existing Bazel binary.
### Step 1: Download Bazel's sources (distribution archive)
(This step is the same for all platforms.)
1. Download `bazel--dist.zip` from
[GitHub](https://github.com/bazelbuild/bazel/releases/latest), for example
`bazel-0.28.1-dist.zip`.
**Attention**:
* There is a **single, architecture-independent** distribution archive.
There are no architecture-specific or OS-specific distribution archives.
* These sources are **not the same as the GitHub source tree**. You
have to use the distribution archive to bootstrap Bazel. You cannot
use a source tree cloned from GitHub. (The distribution archive contains
generated source files that are required for bootstrapping and are not part
of the normal Git source tree.)
2. Unpack the distribution archive somewhere on disk.
You should verify the signature made by Bazel's
[release key](https://releases.bazel.build/bazel-release.pub.gpg) 3D5919B448457EE0.
### Step 2a: Bootstrap Bazel on Ubuntu Linux, macOS, and other Unix-like systems
For instructions for Windows, see [Bootstrap Bazel on Windows](#bootstrap-windows).
#### 2.1. Install the prerequisites
* **Bash**
* **zip, unzip**
* **C++ build toolchain**
* **JDK.** Version 25 is required.
* **Python**. Version 3 is required.
For example on Ubuntu Linux you can install these requirements using the
following command:
```sh theme={null}
sudo apt-get install build-essential openjdk-25-jdk python3 zip unzip
```
#### 2.2. Bootstrap Bazel on Unix
1. Open a shell or Terminal window.
2. `cd` to the directory where you unpacked the distribution archive.
3. Run the compilation script: `env EXTRA_BAZEL_ARGS="--tool_java_runtime_version=local_jdk" bash ./compile.sh`.
The compiled output is placed into `output/bazel`. This is a self-contained
Bazel binary, without an embedded JDK. You can copy it anywhere or use it
in-place. For convenience, copy this binary to a directory that's on your
`PATH` (such as `/usr/local/bin` on Linux).
To build the `bazel` binary in a reproducible way, also set
[`SOURCE_DATE_EPOCH`](https://reproducible-builds.org/specs/source-date-epoch/)
in the "Run the compilation script" step.
### Step 2b: Bootstrap Bazel on Windows
For instructions for Unix-like systems, see
[Bootstrap Bazel on Ubuntu Linux, macOS, and other Unix-like systems](#bootstrap-unix).
#### 2.1. Install the prerequisites
* [MSYS2 shell](https://msys2.github.io/)
* **The MSYS2 packages for zip and unzip.** Run the following command in the MSYS2 shell:
```
pacman -S zip unzip patch
```
* **The Visual C++ compiler.** Install the Visual C++ compiler either as part
of Visual Studio 2015 or newer, or by installing the latest [Build Tools for Visual Studio 2017](https://aka.ms/BuildTools).
* **JDK.** Version 25 is required.
* **Python**. Versions 2 and 3 are supported, installing one of them is
enough. You need the Windows-native version (downloadable from
[https://www.python.org](https://www.python.org)). Versions installed via
pacman in MSYS2 will not work.
#### 2.2. Bootstrap Bazel on Windows
1. Open the MSYS2 shell.
2. Set the following environment variables:
* Either `BAZEL_VS` or `BAZEL_VC` (they are *not* the same): Set to the
path to the Visual Studio directory (BAZEL\_VS) or to the Visual
C++ directory (BAZEL\_VC). Setting one of them is enough.
* `BAZEL_SH`: Path of the MSYS2 `bash.exe`. See the command in the
examples below.
Do not set this to `C:\Windows\System32\bash.exe`. (You have that file
if you installed Windows Subsystem for Linux.) Bazel does not support
this version of `bash.exe`.
* `PATH`: Add the Python directory.
* `JAVA_HOME`: Set to the JDK directory.
**Example** (using BAZEL\_VS):
export BAZEL\_VS="C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools"
export BAZEL\_SH="$(cygpath -m $(realpath $(which bash)))"
export PATH="/c/python27:$PATH"
export JAVA\_HOME="C:/Program Files/Java/jdk-25"
or (using BAZEL\_VC):
export BAZEL\_VC="C:/Program Files (x86)/Microsoft Visual Studio/2017/BuildTools/VC"
export BAZEL\_SH="$(cygpath -m $(realpath $(which bash)))"
export PATH="/c/python27:$PATH"
export JAVA\_HOME="C:/Program Files/Java/jdk-25"
3. `cd` to the directory where you unpacked the distribution archive.
4. Run the compilation script: `env EXTRA_BAZEL_ARGS="--tool_java_runtime_version=local_jdk" ./compile.sh`
The compiled output is placed into `output/bazel.exe`. This is a self-contained
Bazel binary, without an embedded JDK. You can copy it anywhere or use it
in-place. For convenience, copy this binary to a directory that's on
your `PATH`.
To build the `bazel.exe` binary in a reproducible way, also set
[`SOURCE_DATE_EPOCH`](https://reproducible-builds.org/specs/source-date-epoch/)
in the "Run the compilation script" step.
You don't need to run Bazel from the MSYS2 shell. You can run Bazel from the
Command Prompt (`cmd.exe`) or PowerShell.
# Command-Line Completion
Source: https://bazel.build/install/completion
You can enable command-line completion (also known as tab-completion) in Bash
and Zsh. This lets you tab-complete command names, flags names and flag values,
and target names.
## Bash
Bazel comes with a Bash completion script.
If you installed Bazel:
* From the APT repository, then you're done -- the Bash completion script is
already installed in `/etc/bash_completion.d`.
* From Homebrew, then you're done -- the Bash completion script is
already installed in `$(brew --prefix)/etc/bash_completion.d`.
* From the installer downloaded from GitHub, then:
1. Locate the absolute path of the completion file. The installer copied it
to the `bin` directory.
Example: if you ran the installer with `--user`, this will be
`$HOME/.bazel/bin`. If you ran the installer as root, this will be
`/usr/local/lib/bazel/bin`.
2. Do one of the following:
* Either copy this file to your completion directory (if you have
one).
Example: on Ubuntu this is the `/etc/bash_completion.d` directory.
* Or source the completion file from Bash's RC file.
Add a line similar to the one below to your `~/.bashrc` (on Ubuntu)
or `~/.bash_profile` (on macOS), using the path to your completion
file's absolute path:
```
source /path/to/bazel-complete.bash
```
* Via [bootstrapping](/install/compile-source), then:
1. Emit the completion script into a file:
```
bazel help completion bash > bazel-complete.bash
```
2. Do one of the following:
* Copy this file to your completion directory, if you have
one.
Example: on Ubuntu this is the `/etc/bash_completion.d` directory
* Copy it somewhere on your local disk, such as to `$HOME`, and
source the completion file from Bash's RC file.
Add a line similar to the one below to your `~/.bashrc` (on Ubuntu)
or `~/.bash_profile` (on macOS), using the path to your completion
file's absolute path:
```
source /path/to/bazel-complete.bash
```
## Zsh
Bazel comes with a Zsh completion script.
If you installed Bazel:
* From the APT repository, then you're done -- the Zsh completion script is
already installed in `/usr/share/zsh/vendor-completions`.
> If you have a heavily customized `.zshrc` and the autocomplete
> does not function, try one of the following solutions:
>
> Add the following to your `.zshrc`:
>
> ```
> zstyle :compinstall filename '/home/tradical/.zshrc'
>
> autoload -Uz compinit
> compinit
> ```
>
> or
>
> Follow the instructions
> [here](https://stackoverflow.com/questions/58331977/bazel-tab-auto-complete-in-zsh-not-working)
>
> If you are using `oh-my-zsh`, you may want to install and enable
> the `zsh-autocomplete` plugin. If you'd prefer not to, use one of the
> solutions described above.
* From Homebrew, then you're done -- the Zsh completion script is
already installed in `$(brew --prefix)/share/zsh/site-functions`.
* From the installer downloaded from GitHub, then:
1. Locate the absolute path of the completion file. The installer copied it
to the `bin` directory.
Example: if you ran the installer with `--user`, this will be
`$HOME/.bazel/bin`. If you ran the installer as root, this will be
`/usr/local/lib/bazel/bin`.
2. Add this script to a directory on your `$fpath`:
```
fpath[1,0]=~/.zsh/completion/
mkdir -p ~/.zsh/completion/
cp /path/from/above/step/_bazel ~/.zsh/completion
```
You may have to call `rm -f ~/.zcompdump; compinit`
the first time to make it work.
3. Optionally, add the following to your .zshrc.
```
# This way the completion script does not have to parse Bazel's options
# repeatedly. The directory in cache-path must be created manually.
zstyle ':completion:*' use-cache on
zstyle ':completion:*' cache-path ~/.zsh/cache
```
# Getting Started with Bazel Docker Container
Source: https://bazel.build/install/docker-container
This page provides details on the contents of the Bazel container, how to build
the [abseil-cpp](https://github.com/abseil/abseil-cpp) project using Bazel
inside the Bazel container, and how to build this project directly
from the host machine using the Bazel container with directory mounting.
## Build Abseil project from your host machine with directory mounting
The instructions in this section allow you to build using the Bazel container
with the sources checked out in your host environment. A container is started up
for each build command you execute. Build results are cached in your host
environment so they can be reused across builds.
Clone the project to a directory in your host machine.
```posix-terminal theme={null}
git clone --depth 1 --branch 20220623.1 https://github.com/abseil/abseil-cpp.git /src/workspace
```
Create a folder that will have cached results to be shared across builds.
```posix-terminal theme={null}
mkdir -p /tmp/build_output/
```
Use the Bazel container to build the project and make the build
outputs available in the output folder in your host machine.
```posix-terminal theme={null}
docker run \
-e USER="$(id -u)" \
-u="$(id -u)" \
-v /src/workspace:/src/workspace \
-v /tmp/build_output:/tmp/build_output \
-w /src/workspace \
gcr.io/bazel-public/bazel:latest \
--output_user_root=/tmp/build_output \
build //absl/...
```
Build the project with sanitizers by adding the `--config=asan|tsan|msan` build
flag to select AddressSanitizer (asan), ThreadSanitizer (tsan) or
MemorySanitizer (msan) accordingly.
```posix-terminal theme={null}
docker run \
-e USER="$(id -u)" \
-u="$(id -u)" \
-v /src/workspace:/src/workspace \
-v /tmp/build_output:/tmp/build_output \
-w /src/workspace \
gcr.io/bazel-public/bazel:latest \
--output_user_root=/tmp/build_output \
build --config={asan | tsan | msan} -- //absl/... -//absl/types:variant_test
```
## Build Abseil project from inside the container
The instructions in this section allow you to build using the Bazel container
with the sources inside the container. By starting a container at the beginning
of your development workflow and doing changes in the worskpace within the
container, build results will be cached.
Start a shell in the Bazel container:
```posix-terminal theme={null}
docker run --interactive --entrypoint=/bin/bash gcr.io/bazel-public/bazel:latest
```
Each container id is unique. In the instructions below, the container was 5a99103747c6.
Clone the project.
```posix-terminal theme={null}
ubuntu@5a99103747c6:~$ git clone --depth 1 --branch 20220623.1 https://github.com/abseil/abseil-cpp.git && cd abseil-cpp/
```
Do a regular build.
```posix-terminal theme={null}
ubuntu@5a99103747c6:~/abseil-cpp$ bazel build //absl/...
```
Build the project with sanitizers by adding the `--config=asan|tsan|msan`
build flag to select AddressSanitizer (asan), ThreadSanitizer (tsan) or
MemorySanitizer (msan) accordingly.
```posix-terminal theme={null}
ubuntu@5a99103747c6:~/abseil-cpp$ bazel build --config={asan | tsan | msan} -- //absl/... -//absl/types:variant_test
```
## Explore the Bazel container
If you haven't already, start an interactive shell inside the Bazel container.
```posix-terminal theme={null}
docker run -it --entrypoint=/bin/bash gcr.io/bazel-public/bazel:latest
ubuntu@5a99103747c6:~$
```
Explore the container contents.
```posix-terminal theme={null}
ubuntu@5a99103747c6:~$ gcc --version
gcc (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
ubuntu@5a99103747c6:~$ java -version
openjdk version "1.8.0_362"
OpenJDK Runtime Environment (build 1.8.0_362-8u372-ga~us1-0ubuntu1~20.04-b09)
OpenJDK 64-Bit Server VM (build 25.362-b09, mixed mode)
ubuntu@5a99103747c6:~$ python -V
Python 3.8.10
ubuntu@5a99103747c6:~$ bazel version
WARNING: Invoking Bazel in batch mode since it is not invoked from within a workspace (below a directory having a WORKSPACE file).
Extracting Bazel installation...
Build label: 6.2.1
Build target: bazel-out/k8-opt/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Fri Jun 2 16:59:58 2023 (1685725198)
Build timestamp: 1685725198
Build timestamp as int: 1685725198
```
## Explore the Bazel Dockerfile
If you want to check how the Bazel Docker image is built, you can find its Dockerfile at [bazelbuild/continuous-integration/bazel/oci](https://github.com/bazelbuild/continuous-integration/tree/master/bazel/oci).
# Integrating Bazel with IDEs
Source: https://bazel.build/install/ide
This page covers how to integrate Bazel with IDEs, such as IntelliJ, Android
Studio, and CLion (or build your own IDE plugin). It also includes links to
installation and plugin details.
IDEs integrate with Bazel in a variety of ways, from features that allow Bazel
executions from within the IDE, to awareness of Bazel structures such as syntax
highlighting of the `BUILD` files.
If you are interested in developing an editor or IDE plugin for Bazel, please
join the `#ide` channel on the [Bazel Slack](https://slack.bazel.build) or start
a discussion on [GitHub](https://github.com/bazelbuild/bazel/discussions).
## IDEs and editors
### IntelliJ, Android Studio, and CLion
Official Bazel plugins exist for many of the JetBrains-associated IDEs.
Full documentation is linked from the listings on the JetBrains Marketplace:
* [IntelliJ plugin](https://plugins.jetbrains.com/plugin/22977-bazel)
* [Android Studio plugin](https://plugins.jetbrains.com/plugin/9185-android-studio-with-bazel)
* [CLion plugin](https://plugins.jetbrains.com/plugin/9554-clion-with-bazel)
Features:
* Interop with language-specific plugins. Supported languages include Java,
Scala, and Python.
* Import `BUILD` files into the IDE with semantic awareness of Bazel targets.
* Make your IDE aware of Starlark, the language used for Bazel's `BUILD` and
`.bzl`files
* Build, test, and execute binaries directly from the IDE
* Create configurations for debugging and running binaries.
To install, go to the IDE's plugin browser and search for `Bazel`.
To manually install older versions, download the zip files from the JetBrains
Marketplace or from [GitHub Releases](https://github.com/bazelbuild/intellij/releases)
and install the zip file from the IDE's plugin browser.
### Xcode
[rules\_xcodeproj](https://github.com/MobileNativeFoundation/rules_xcodeproj)
generates Xcode projects from Bazel `BUILD` files.
### Visual Studio Code
Official plugin for VS Code.
Features:
* Bazel Build Targets tree
* Starlark debugger for `.bzl` files during a build (set breakpoints, step
through code, inspect variables, and so on)
Find [the plugin on the Visual Studio marketplace](https://marketplace.visualstudio.com/items?itemName=BazelBuild.vscode-bazel)
or the [OpenVSX marketplace](https://open-vsx.org/extension/BazelBuild/vscode-bazel).
The plugin is [open source](https://github.com/bazelbuild/vscode-bazel).
See also: [Autocomplete for Source Code](#autocomplete-for-source-code)
### Atom
Find the [`language-bazel` package](https://atom.io/packages/language-bazel)
on the Atom package manager.
See also: [Autocomplete for Source Code](#autocomplete-for-source-code)
### Vim
See [`bazelbuild/vim-bazel` on GitHub](https://github.com/bazelbuild/vim-bazel)
See also: [Autocomplete for Source Code](#autocomplete-for-source-code)
### Emacs
See [`bazelbuild/bazel-emacs-mode` on GitHub](https://github.com/bazelbuild/emacs-bazel-mode)
See also: [Autocomplete for Source Code](#autocomplete-for-source-code)
### Visual Studio
[Lavender](https://github.com/tmandry/lavender) is an experimental project for
generating Visual Studio projects that use Bazel for building.
### Eclipse
[Bazel Eclipse Feature](https://github.com/salesforce/bazel-eclipse)
is a set of plugins for importing Bazel packages into an Eclipse workspace as
Eclipse projects.
## Autocomplete for Source Code
### C Language Family (C++, C, Objective-C, Objective-C++, and CUDA)
[`kiron1/bazel-compile-commands`](https://github.com/kiron1/bazel-compile-commands)
run `bazel-compile-commands //...` in a Bazel workspace to generate a `compile_commands.json` file.
The `compile_commands.json` file enables tools like `clang-tidy`, `clangd` (LSP) and other IDEs to
provide autocomplete, smart navigation, quick fixes, and more. The tool is written in C++ and
consumes the Protobuf output of Bazel to extract the compile commands.
[`hedronvision/bazel-compile-commands-extractor`](https://github.com/hedronvision/bazel-compile-commands-extractor) enables autocomplete, smart navigation, quick fixes, and more in a wide variety of extensible editors, including VSCode, Vim, Emacs, Atom, and Sublime. It lets language servers, like clangd and ccls, and other types of tooling, draw upon Bazel's understanding of how `cc` and `objc` code will be compiled, including how it configures cross-compilation for other platforms.
### Java
[`georgewfraser/java-language-server`](https://github.com/georgewfraser/java-language-server) - Java Language Server (LSP) with support for Bazel-built projects
## Automatically run build and test on file change
[Bazel watcher](https://github.com/bazelbuild/bazel-watcher) is a
tool for building Bazel targets when source files change.
## Building your own IDE plugin
Read the [**IDE support** blog post](https://blog.bazel.build/2016/06/10/ide-support.html) to learn more about
the Bazel APIs to use when building an IDE plugin.
# Installing Bazel
Source: https://bazel.build/install/index
This page describes the various platforms supported by Bazel and links
to the packages for more details.
[Bazelisk](/install/bazelisk) is the recommended way to install Bazel on [Ubuntu Linux](/install/ubuntu), [macOS](/install/os-x), and [Windows](/install/windows).
You can find available Bazel releases on our [release page](/release).
## Community-supported packages
Bazel community members maintain these packages. The Bazel team doesn't
officially support them. Contact the package maintainers for support.
* [Alpine Linux](https://pkgs.alpinelinux.org/packages?name=bazel*\&branch=edge\&repo=\&arch=\&origin=\&flagged=\&maintainer=)
* [Arch Linux][arch]
* [Debian](https://qa.debian.org/developer.php?email=team%2Bbazel%40tracker.debian.org)
* [Fedora](https://copr.fedorainfracloud.org/coprs/lihaohong/bazel)
* [FreeBSD](https://www.freshports.org/devel/bazel)
* [Homebrew](https://formulae.brew.sh/formula/bazel)
* [mise](/install/mise)
* [Nixpkgs](https://github.com/NixOS/nixpkgs/tree/master/pkgs/by-name/ba/bazel_9)
* [openSUSE](/install/suse)
* [Scoop](https://github.com/scoopinstaller/scoop-main/blob/master/bucket/bazel.json)
* [Raspberry Pi](https://github.com/koenvervloesem/bazel-on-arm/blob/master/README.md)
## Community-supported architectures
* [ppc64el](https://ftp2.osuosl.org/pub/ppc64el/bazel/)
For other platforms, you can try to [compile from source](/install/compile-source).
[arch]: https://archlinux.org/packages/extra/x86_64/bazel/
# Installing Bazel with mise
Source: https://bazel.build/install/mise
This page describes how to install Bazel using [mise](https://github.com/jdx/mise) the polyglot tools version manager.
```shell theme={null}
mise use -g bazel@latest
```
# Installing Bazel on macOS
Source: https://bazel.build/install/os-x
This page describes how to install Bazel on macOS and set up your environment.
You can install Bazel on macOS using one of the following methods:
* *Recommended*: [Use Bazelisk](/install/bazelisk)
* [Use Homebrew](#install-on-mac-os-x-homebrew)
* [Use the binary installer](#install-with-installer-mac-os-x)
* [Compile Bazel from source](/install/compile-source)
Bazel comes with two completion scripts. After installing Bazel, you can:
* Access the [bash completion script](/install/completion#bash)
* Install the [zsh completion script](/install/completion#zsh)
Installing using Homebrew
### Step 1: Install Homebrew on macOS
Install [Homebrew](https://brew.sh/) (a one-time step):
```posix-terminal theme={null}
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
```
### Step 2: Install Bazel via Homebrew
Install the Bazel package via Homebrew as follows:
```posix-terminal theme={null}
brew install bazel
```
All set! You can confirm Bazel is installed successfully by running the
following command:
```posix-terminal theme={null}
bazel --version
```
Once installed, you can upgrade to a newer version of Bazel using the
following command:
```posix-terminal theme={null}
brew upgrade bazel
```
Installing using the binary installer
The binary installers are on Bazel's
[GitHub releases page](https://github.com/bazelbuild/bazel/releases).
The installer contains the Bazel binary. Some additional libraries
must also be installed for Bazel to work.
### Step 1: Install Xcode command line tools
If you don't intend to use `ios_*` rules, it is sufficient to install the Xcode
command line tools package by using `xcode-select`:
```posix-terminal theme={null}
xcode-select --install
```
Otherwise, for `ios_*` rule support, you must have Xcode 6.1 or later with iOS
SDK 8.1 installed on your system.
Download Xcode from the
[App Store](https://apps.apple.com/us/app/xcode/id497799835) or the
[Apple Developer site](https://developer.apple.com/download/more/?=xcode).
Once Xcode is installed, accept the license agreement for all users with the
following command:
```posix-terminal theme={null}
sudo xcodebuild -license accept
```
### Step 2: Download the Bazel installer
Next, download the Bazel binary installer named
`bazel--installer-darwin-x86_64.sh` from the
[Bazel releases page on GitHub](https://github.com/bazelbuild/bazel/releases).
**On macOS Catalina or newer (macOS >= 11)**, due to Apple's new app signing requirements,
you need to download the installer from the terminal using `curl`, replacing
the version variable with the Bazel version you want to download:
```posix-terminal theme={null}
export BAZEL_VERSION=5.2.0
curl -fLO "https://github.com/bazelbuild/bazel/releases/download/$BAZEL_VERSION/bazel-$BAZEL_VERSION-installer-darwin-x86_64.sh"
```
This is a temporary workaround until the macOS release flow supports
signing ([#9304](https://github.com/bazelbuild/bazel/issues/9304)).
### Step 3: Run the installer
Run the Bazel installer as follows:
```posix-terminal theme={null}
chmod +x "bazel-$BAZEL_VERSION-installer-darwin-x86_64.sh"
./bazel-$BAZEL_VERSION-installer-darwin-x86_64.sh --user
```
The `--user` flag installs Bazel to the `$HOME/bin` directory on your system and
sets the `.bazelrc` path to `$HOME/.bazelrc`. Use the `--help` command to see
additional installation options.
If you are **on macOS Catalina or newer (macOS >= 11)** and get an error that ***“bazel-real” cannot be
opened because the developer cannot be verified***, you need to re-download
the installer from the terminal using `curl` as a workaround; see Step 2 above.
### Step 4: Set up your environment
If you ran the Bazel installer with the `--user` flag as above, the Bazel
executable is installed in your `HOME/bin` directory.
It's a good idea to add this directory to your default paths, as follows:
```posix-terminal theme={null}
export PATH="PATH:HOME/bin"
```
You can also add this command to your `~/.bashrc`, `~/.zshrc`, or `~/.profile`
file.
All set! You can confirm Bazel is installed successfully by running the
following command:
```posix-terminal theme={null}
bazel --version
```
To update to a newer release of Bazel, download and install the desired version.
# Installing Bazel on openSUSE Tumbleweed & Leap
Source: https://bazel.build/install/suse
This page describes how to install Bazel on openSUSE Tumbleweed and Leap.
`NOTE:` The Bazel team does not officially maintain openSUSE support. For issues
using Bazel on openSUSE please file a ticket at [bugzilla.opensuse.org](https://bugzilla.opensuse.org/).
Packages are provided for openSUSE Tumbleweed and Leap. You can find all
available Bazel versions via openSUSE's [software search](https://software.opensuse.org/search?utf8=%E2%9C%93\&baseproject=ALL\&q=bazel).
The commands below must be run either via `sudo` or while logged in as `root`.
## Installing Bazel on openSUSE
Run the following commands to install the package. If you need a specific
version, you can install it via the specific `bazelXXX` package, otherwise,
just `bazel` is enough:
To install the latest version of Bazel, run:
```posix-terminal theme={null}
zypper install bazel
```
You can also install a specific version of Bazel by specifying the package
version with `bazelversion`. For example, to install
Bazel 4.2, run:
```posix-terminal theme={null}
zypper install bazel4.2
```
# Installing Bazel on Ubuntu
Source: https://bazel.build/install/ubuntu
This page describes the options for installing Bazel on Ubuntu.
It also provides links to the Bazel completion scripts and the binary installer,
if needed as a backup option (for example, if you don't have admin access).
Supported Ubuntu Linux platforms:
* 22.04 (LTS)
* 20.04 (LTS)
* 18.04 (LTS)
Bazel should be compatible with other Ubuntu releases and Debian
"stretch" and above, but is untested and not guaranteed to work.
Install Bazel on Ubuntu using one of the following methods:
* *Recommended*: [Use Bazelisk](/install/bazelisk)
* [Use our custom APT repository](#install-on-ubuntu)
* [Use the binary installer](#binary-installer)
* [Use the Bazel Docker container](#docker-container)
* [Compile Bazel from source](/install/compile-source)
**Note:** For Arm-based systems, the APT repository does not contain an `arm64`
release, and there is no binary installer available. Either use Bazelisk or
compile from source.
Bazel comes with two completion scripts. After installing Bazel, you can:
* Access the [bash completion script](/install/completion#bash)
* Install the [zsh completion script](/install/completion#zsh)
## Using Bazel's apt repository
### Step 1: Add Bazel distribution URI as a package source
**Note:** This is a one-time setup step.
```posix-terminal theme={null}
sudo apt install apt-transport-https curl gnupg -y
curl -fsSL https://releases.bazel.build/bazel-release.pub.gpg | gpg --dearmor >bazel-archive-keyring.gpg
sudo mv bazel-archive-keyring.gpg /usr/share/keyrings
echo "deb [arch=amd64 signed-by=/usr/share/keyrings/bazel-archive-keyring.gpg] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list
```
The component name "jdk1.8" is kept only for legacy reasons and doesn't relate
to supported or included JDK versions. Bazel releases are Java-version agnostic.
Changing the "jdk1.8" component name would break existing users of the repo.
### Step 2: Install and update Bazel
```posix-terminal theme={null}
sudo apt update && sudo apt install bazel
```
Once installed, you can upgrade to a newer version of Bazel as part of your normal system updates:
```posix-terminal theme={null}
sudo apt update && sudo apt full-upgrade
```
The `bazel` package always installs the latest stable version of Bazel. You
can install specific, older versions of Bazel in addition to the latest one,
such as this:
```posix-terminal theme={null}
sudo apt install bazel-1.0.0
```
This installs Bazel 1.0.0 as `/usr/bin/bazel-1.0.0` on your system. This
can be useful if you need a specific version of Bazel to build a project, for
example because it uses a `.bazelversion` file to explicitly state with which
Bazel version it should be built.
Optionally, you can set `bazel` to a specific version by creating a symlink:
```posix-terminal theme={null}
sudo ln -s /usr/bin/bazel-1.0.0 /usr/bin/bazel
bazel --version # 1.0.0
```
### Step 3: Install a JDK (optional)
Bazel includes a private, bundled JRE as its runtime and doesn't require you to
install any specific version of Java.
However, if you want to build Java code using Bazel, you have to install a JDK.
```posix-terminal theme={null}
sudo apt install default-jdk
```
## Using the binary installer
Generally, you should use the apt repository, but the binary installer
can be useful if you don't have admin permissions on your machine or
can't add custom repositories.
The binary installers can be downloaded from Bazel's [GitHub releases page](https://github.com/bazelbuild/bazel/releases).
The installer contains the Bazel binary and extracts it into your `$HOME/bin`
folder. Some additional libraries must be installed manually for Bazel to work.
### Step 1: Install required packages
Bazel needs a C++ compiler and unzip / zip in order to work:
```posix-terminal theme={null}
sudo apt install g++ unzip zip
```
If you want to build Java code using Bazel, install a JDK:
```posix-terminal theme={null}
sudo apt-get install default-jdk
```
### Step 2: Run the installer
Next, download the Bazel binary installer named `bazel-version-installer-linux-x86_64.sh`
from the [Bazel releases page on GitHub](https://github.com/bazelbuild/bazel/releases).
Run it as follows:
```posix-terminal theme={null}
chmod +x bazel-version-installer-linux-x86_64.sh
./bazel-version-installer-linux-x86_64.sh --user
```
The `--user` flag installs Bazel to the `$HOME/bin` directory on your system and
sets the `.bazelrc` path to `$HOME/.bazelrc`. Use the `--help` command to see
additional installation options.
### Step 3: Set up your environment
If you ran the Bazel installer with the `--user` flag as above, the Bazel
executable is installed in your `$HOME/bin` directory.
It's a good idea to add this directory to your default paths, as follows:
```posix-terminal theme={null}
export PATH="$PATH:$HOME/bin"
```
You can also add this command to your `~/.bashrc` or `~/.zshrc` file to make it
permanent.
## Using the Bazel Docker container
We publish Docker container with Bazel installed for each Bazel version at `gcr.io/bazel-public/bazel`.
You can use the Docker container as follows:
```
$ docker pull gcr.io/bazel-public/bazel:
```
The Docker container is built by [these steps](https://github.com/bazelbuild/continuous-integration/tree/master/bazel/oci).
# Installing Bazel on Windows
Source: https://bazel.build/install/windows
This page describes the requirements and steps to install Bazel on Windows.
It also includes troubleshooting and other ways to install Bazel, such as
using Chocolatey or Scoop.
## Installing Bazel
This section covers the prerequisites, environment setup, and detailed
steps during installation on Windows.
### Check your system
Recommended: 64 bit Windows 10, version 1703 (Creators Update) or newer
To check your Windows version:
* Click the Start button.
* Type `winver` in the search box and press Enter.
* You should see the About Windows box with your Windows version information.
### Install the prerequisites
* [Microsoft Visual C++ Redistributable](https://learn.microsoft.com/en-us/cpp/windows/latest-supported-vc-redist?view=msvc-170)
### Download Bazel
*Recommended*: [Use Bazelisk](/install/bazelisk)
Alternatively you can:
* [Download the Bazel binary (`bazel-version-windows-x86_64.exe`) from GitHub](https://github.com/bazelbuild/bazel/releases).
* [Install Bazel from Chocolatey](#chocolately)
* [Install Bazel from Scoop](#scoop)
* [Build Bazel from source](/install/compile-source)
### Set up your environment
To make Bazel easily accessible from command prompts or PowerShell by default, you can rename the Bazel binary to `bazel.exe` and add it to your default paths.
```posix-terminal theme={null}
set PATH=%PATH%;path to the Bazel binary
```
You can also change your system `PATH` environment variable to make it permanent. Check out how to [set environment variables](/configure/windows#set-environment-variables).
### Done
"Success: You've installed Bazel."
To check the installation is correct, try to run:
```posix-terminal theme={null}
bazel version
```
Next, you can check out more tips and guidance here:
* [Installing compilers and language runtimes](#install-compilers)
* [Troubleshooting](#troubleshooting)
* [Best practices on Windows](/configure/windows#best-practices)
* [Tutorials](/start/#tutorials)
## Installing compilers and language runtimes
Depending on which languages you want to build, you will need:
* [MSYS2 x86\_64](https://www.msys2.org/)
MSYS2 is a software distro and building platform for Windows. It contains Bash and common Unix
tools (like `grep`, `tar`, `git`).
You will need MSYS2 to build, test, or run targets that depend on Bash. Typically these are
`genrule`, `sh_binary`, `sh_test`, but there may be more (such as Starlark rules). Bazel shows an
error if a build target needs Bash but Bazel could not locate it.
* Common MSYS2 packages
You will likely need these to build and run targets that depend on Bash. MSYS2 does not install
these tools by default, so you need to install them manually. Projects that depend on Bash tools in `PATH` need this step (for example TensorFlow).
Open the MSYS2 terminal and run this command:
```posix-terminal theme={null}
pacman -S zip unzip patch diffutils git
```
Optional: If you want to use Bazel from CMD or Powershell and still be able
to use Bash tools, make sure to add
`MSYS2_INSTALL_PATH/usr/bin` to your
`PATH` environment variable.
* [Build Tools for Visual Studio 2019](https://aka.ms/buildtools)
You will need this to build C++ code on Windows.
Also supported:
* Visual C++ Build Tools 2017 (or newer) and Windows 10 SDK
* [Java SE Development Kit 11 (JDK) for Windows x64](https://www.oracle.com/java/technologies/javase-jdk11-downloads.html)
You will need this to build Java code on Windows.
Also supported: Java 8, 9, and 10
* [Python 3.6 for Windows x86-64](https://www.python.org/downloads/windows/)
You will need this to build Python code on Windows.
Also supported: Python 2.7 or newer for Windows x86-64
## Troubleshooting
### Bazel does not find Bash or bash.exe
**Possible reasons**:
* you installed MSYS2 not under the default install path
* you installed MSYS2 i686 instead of MSYS2 x86\_64
* you installed MSYS instead of MSYS2
**Solution**:
Ensure you installed MSYS2 x86\_64.
If that doesn't help:
1. Go to Start Menu > Settings.
2. Find the setting "Edit environment variables for your account"
3. Look at the list on the top ("User variables for \"), and click the "New\..."
button below it.
4. For "Variable name", enter `BAZEL_SH`
5. Click "Browse File..."
6. Navigate to the MSYS2 directory, then to `usr\bin` below it.
For example, this might be `C:\msys64\usr\bin` on your system.
7. Select the `bash.exe` or `bash` file and click OK
8. The "Variable value" field now has the path to `bash.exe`. Click OK to close the window.
9. Done.
If you open a new cmd.exe or PowerShell terminal and run Bazel now, it will find Bash.
### Bazel does not find Visual Studio or Visual C++
**Possible reasons**:
* you installed multiple versions of Visual Studio
* you installed and removed various versions of Visual Studio
* you installed various versions of the Windows SDK
* you installed Visual Studio not under the default install path
**Solution**:
1. Go to Start Menu > Settings.
2. Find the setting "Edit environment variables for your account"
3. Look at the list on the top ("User variables for \"), and click the "New\..."
button below it.
4. For "Variable name", enter `BAZEL_VC`
5. Click "Browse Directory..."
6. Navigate to the `VC` directory of Visual Studio.
For example, this might be `C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC`
on your system.
7. Select the `VC` folder and click OK
8. The "Variable value" field now has the path to `VC`. Click OK to close the window.
9. Done.
If you open a new cmd.exe or PowerShell terminal and run Bazel now, it will find Visual C++.
## Other ways to install Bazel
### Using Chocolatey
1. Install the [Chocolatey](https://chocolatey.org) package manager
2. Install the Bazel package:
```posix-terminal theme={null}
choco install bazel
```
This command will install the latest available version of Bazel and
its dependencies, such as the MSYS2 shell. This will not install Visual C++
though.
See [Chocolatey installation and package maintenance guide](/contribute/windows-chocolatey-maintenance) for more
information about the Chocolatey package.
### Using Scoop
1. Install the [Scoop](https://scoop.sh/) package manager using the following PowerShell command:
```posix-terminal theme={null}
iex (new-object net.webclient).downloadstring('https://get.scoop.sh')
```
2. Install the Bazel package:
```posix-terminal theme={null}
scoop install bazel
```
See [Scoop installation and package maintenance guide](/contribute/windows-scoop-maintenance) for more
information about the Scoop package.
### Build from source
To build Bazel from scratch instead of installing, see [Compiling from source](/install/compile-source).
# Migrating to Bazel
Source: https://bazel.build/migrate/index
This page links to migration guides for Bazel.
* [Maven](/migrate/maven)
* [Xcode](/migrate/xcode)
# Migrating from Maven to Bazel
Source: https://bazel.build/migrate/maven
This page describes how to migrate from Maven to Bazel, including the
prerequisites and installation steps. It describes the differences between Maven
and Bazel, and provides a migration example using the Guava project.
When migrating from any build tool to Bazel, it's best to have both build tools
running in parallel until you have fully migrated your development team, CI
system, and any other relevant systems. You can run Maven and Bazel in the same
repository.
Note: While Bazel supports downloading and publishing Maven artifacts with
[rules\_jvm\_external](https://github.com/bazelbuild/rules_jvm_external)
, it does not directly support Maven-based plugins. Maven plugins can't be
directly run by Bazel since there's no Maven compatibility layer.
## Before you begin
* [Install Bazel](/install) if it's not yet installed.
* If you're new to Bazel, go through the tutorial [Introduction to Bazel: Build Java](/start/java) before you start migrating. The tutorial explains
Bazel's concepts, structure, and label syntax.
## Differences between Maven and Bazel
* Maven uses top-level `pom.xml` file(s). Bazel supports multiple build files
and multiple targets per `BUILD` file, allowing for builds that are more
incremental than Maven's.
* Maven takes charge of steps for the deployment process. Bazel does not
automate deployment.
* Bazel enables you to express dependencies between languages.
* As you add new sections to the project, with Bazel you may need to add new
`BUILD` files. Best practice is to add a `BUILD` file to each new Java
package.
## Migrate from Maven to Bazel
The steps below describe how to migrate your project to Bazel:
1. [Create the MODULE.bazel file](#1-build)
2. [Create one BUILD file](#2-build)
3. [Create more BUILD files](#3-build)
4. [Build using Bazel](#4-build)
Examples below come from a migration of the [Guava project](https://github.com/google/guava) from Maven to Bazel. The
Guava project used is release `v31.1`. The examples using Guava do not walk
through each step in the migration, but they do show the files and contents that
are generated or added manually for the migration.
```
$ git clone https://github.com/google/guava.git && cd guava
$ git checkout v31.1
```
1. Create the MODULE.bazel file
Create a file named `MODULE.bazel` at the root of your project. If your project
has no external dependencies, this file can be empty.
If your project depends on files or packages that are not in one of the
project's directories, specify these external dependencies in the MODULE.bazel
file. You can use `rules_jvm_external` to manage dependencies from Maven. For
instructions about using this ruleset, see [the README](https://github.com/bazelbuild/rules_jvm_external/#rules_jvm_external)
.
#### Guava project example: external dependencies
You can list the external dependencies of the [Guava project](https://github.com/google/guava) with the
[`rules_jvm_external`](https://github.com/bazelbuild/rules_jvm_external)
ruleset.
Add the following snippet to the `MODULE.bazel` file:
```python theme={null}
bazel_dep(name = "rules_jvm_external", version = "6.2")
maven = use_extension("@rules_jvm_external//:extensions.bzl", "maven")
maven.install(
artifacts = [
"com.google.code.findbugs:jsr305:3.0.2",
"com.google.errorprone:error_prone_annotations:2.11.0",
"com.google.j2objc:j2objc-annotations:1.3",
"org.codehaus.mojo:animal-sniffer-annotations:1.20",
"org.checkerframework:checker-qual:3.12.0",
],
repositories = [
"https://repo1.maven.org/maven2",
],
)
use_repo(maven, "maven")
```
2. Create one BUILD file
Now that you have your workspace defined and external dependencies (if
applicable) listed, you need to create `BUILD` files to describe how your
project should be built. Unlike Maven with its one `pom.xml` file, Bazel can use
many `BUILD` files to build a project. These files specify multiple build
targets, which allow Bazel to produce incremental builds.
Add `BUILD` files in stages. Start with adding one `BUILD` file at the root of
your project and using it to do an initial build using Bazel. Then, you refine
your build by adding more `BUILD` files with more granular targets.
1. In the same directory as your `MODULE.bazel` file, create a text file and
name it `BUILD`.
2. In this `BUILD` file, use the appropriate rule to create one target to build
your project. Here are some tips:
* Use the appropriate rule:
* To build projects with a single Maven module, use the
`java_library` rule as follows:
```python theme={null}
java_library(
name = "everything",
srcs = glob(["src/main/java/**/*.java"]),
resources = glob(["src/main/resources/**"]),
deps = ["//:all-external-targets"],
)
```
* To build projects with multiple Maven modules, use the
`java_library` rule as follows:
```python theme={null}
java_library(
name = "everything",
srcs = glob([
"Module1/src/main/java/**/*.java",
"Module2/src/main/java/**/*.java",
...
]),
resources = glob([
"Module1/src/main/resources/**",
"Module2/src/main/resources/**",
...
]),
deps = ["//:all-external-targets"],
)
```
* To build binaries, use the `java_binary` rule:
```python theme={null}
java_binary(
name = "everything",
srcs = glob(["src/main/java/**/*.java"]),
resources = glob(["src/main/resources/**"]),
deps = ["//:all-external-targets"],
main_class = "com.example.Main"
)
```
* Specify the attributes:
* `name`: Give the target a meaningful name. In the examples
above, the target is called "everything."
* `srcs`: Use globbing to list all .java files in your project.
* `resources`: Use globbing to list all resources in your project.
* `deps`: You need to determine which external dependencies your
project needs.
* Take a look at the [example below of this top-level BUILD file](#guava-2) from the migration of the Guava project.
3. Now that you have a `BUILD` file at the root of your project, build your
project to ensure that it works. On the command line, from your workspace
directory, use `bazel build //:everything` to build your project with Bazel.
The project has now been successfully built with Bazel. You will need to add
more `BUILD` files to allow incremental builds of the project.
#### Guava project example: start with one BUILD file
When migrating the Guava project to Bazel, initially one `BUILD` file is used to
build the entire project. Here are the contents of this initial `BUILD` file in
the workspace directory:
```python theme={null}
java_library(
name = "everything",
srcs = glob([
"guava/src/**/*.java",
"futures/failureaccess/src/**/*.java",
]),
javacopts = ["-XepDisableAllChecks"],
deps = [
"@maven//:com_google_code_findbugs_jsr305",
"@maven//:com_google_errorprone_error_prone_annotations",
"@maven//:com_google_j2objc_j2objc_annotations",
"@maven//:org_checkerframework_checker_qual",
"@maven//:org_codehaus_mojo_animal_sniffer_annotations",
],
)
```
3. Create more BUILD files (optional)
Bazel does work with just one `BUILD file`, as you saw after completing your
first build. You should still consider breaking the build into smaller chunks by
adding more `BUILD` files with granular targets.
Multiple `BUILD` files with multiple targets will give the build increased
granularity, allowing:
* increased incremental builds of the project,
* increased parallel execution of the build,
* better maintainability of the build for future users, and
* control over visibility of targets between packages, which can prevent
issues such as libraries containing implementation details leaking into
public APIs.
Tips for adding more `BUILD` files:
* You can start by adding a `BUILD` file to each Java package. Start with Java
packages that have the fewest dependencies and work you way up to packages
with the most dependencies.
* As you add `BUILD` files and specify targets, add these new targets to the
`deps` sections of targets that depend on them. Note that the `glob()`
function does not cross package boundaries, so as the number of packages
grows the files matched by `glob()` will shrink.
* Any time you add a `BUILD` file to a `main` directory, ensure that you add a
`BUILD` file to the corresponding `test` directory.
* Take care to limit visibility properly between packages.
* To simplify troubleshooting errors in your setup of `BUILD` files, ensure
that the project continues to build with Bazel as you add each build file.
Run `bazel build //...` to ensure all of your targets still build.
4. Build using Bazel
You've been building using Bazel as you add `BUILD` files to validate the setup
of the build.
When you have `BUILD` files at the desired granularity, you can use Bazel to
produce all of your builds.
# Migrating from Xcode to Bazel
Source: https://bazel.build/migrate/xcode
This page describes how to build or test an Xcode project with Bazel. It
describes the differences between Xcode and Bazel, and provides the steps for
converting an Xcode project to a Bazel project. It also provides troubleshooting
solutions to address common errors.
## Differences between Xcode and Bazel
* Bazel requires you to explicitly specify every build target and its
dependencies, plus the corresponding build settings via build rules.
* Bazel requires all files on which the project depends to be present within
the workspace directory or specified as dependencies in the `MODULE.bazel`
file.
* When building Xcode projects with Bazel, the `BUILD` file(s) become the
source of truth. If you work on the project in Xcode, you must generate a
new version of the Xcode project that matches the `BUILD` files using
[rules\_xcodeproj](https://github.com/buildbuddy-io/rules_xcodeproj/)
whenever you update the `BUILD` files. Certain changes to the `BUILD` files
such as adding dependencies to a target don't require regenerating the
project which can speed up development. If you're not using Xcode, the
`bazel build` and `bazel test` commands provide build and test capabilities
with certain limitations described later in this guide.
## Before you begin
Before you begin, do the following:
1. [Install Bazel](/install) if you have not already done so.
2. If you're not familiar with Bazel and its concepts, complete the [iOS app tutorial](/start/ios-app)). You should understand the Bazel workspace,
including the `MODULE.bazel` and `BUILD` files, as well as the concepts of
targets, build rules, and Bazel packages.
3. Analyze and understand the project's dependencies.
### Analyze project dependencies
Unlike Xcode, Bazel requires you to explicitly declare all dependencies for
every target in the `BUILD` file.
For more information on external dependencies, see [Working with external dependencies](/docs/external).
## Build or test an Xcode project with Bazel
To build or test an Xcode project with Bazel, do the following:
1. [Create the `MODULE.bazel` file](#create-workspace)
2. [Integrate Swift package dependencies](#integrate-swiftpm)
3. [Create a `BUILD` file:](#create-build-file)
a. [Add the application target](#add-app-target)
b. [(Optional) Add the test target(s)](#add-test-target)
c. [Add the library target(s)](#add-library-target)
4. [(Optional) Granularize the build](#granularize-build)
5. [Run the build](#run-build)
6. [Generate the Xcode project with rules\_xcodeproj](#generate-the-xcode-project-with-rules_xcodeproj)
### Step 1: Create the `MODULE.bazel` file
Create a `MODULE.bazel` file in a new directory. This directory becomes the
Bazel workspace root. If the project uses no external dependencies, this file
can be empty. If the project depends on files or packages that are not in one of
the project's directories, specify these external dependencies in the
`MODULE.bazel` file.
Note: Place the project source code within the directory tree containing the
`MODULE.bazel` file.
### Step 2: Integrate Swift package dependencies
If the Xcode project depends on Swift packages, use [rules\_swift\_package\_manager](https://github.com/cgrindel/rules_swift_package_manager)
to make them available as Bazel targets. It reads the `Package.swift` and
`Package.resolved` files you already know from Swift Package Manager, so you
keep declaring dependencies the same way.
First, add the ruleset and the Swift package extension to your `MODULE.bazel`
file:
```python theme={null}
bazel_dep(name = "rules_swift", version = "4.0.1")
bazel_dep(name = "rules_swift_package_manager", version = "1.23.0")
swift_deps = use_extension(
"@rules_swift_package_manager//:extensions.bzl",
"swift_deps",
)
swift_deps.from_package(
resolved = "//:Package.resolved",
swift = "//:Package.swift",
)
use_repo(swift_deps, "swift_package")
```
Next, create a `Package.swift` file at the workspace root listing only the
packages your Bazel targets depend on directly:
```swift theme={null}
// swift-tools-version: 5.7
import PackageDescription
let package = Package(
name: "my-project",
dependencies: [
.package(url: "https://github.com/apple/swift-log", from: "1.4.4"),
]
)
```
Then resolve the packages and let Bazel record the resulting repositories:
```posix-terminal theme={null}
swift package update
bazel mod tidy
```
`swift package update` writes `Package.resolved`, and `bazel mod tidy` adds each
resolved package to the `use_repo` call in `MODULE.bazel`. Each package becomes
an external repository named `swiftpkg_` plus the package identity, lowercased
with punctuation replaced by underscores, and each product in the package
becomes a target in it. Depend on those targets like any other:
```python theme={null}
load("@rules_swift//swift:swift.bzl", "swift_library")
swift_library(
name = "AppLib",
srcs = glob(["Sources/*.swift"]),
deps = ["@swiftpkg_swift_log//:Logging"],
)
```
Check `Package.swift`, `Package.resolved`, and `MODULE.bazel` into version
control. Re-run both commands above whenever you change `Package.swift`.
Once `Package.resolved` exists, `bazel run @swift_package//:update` and
`bazel run @swift_package//:resolve` replace `swift package update` and
`swift package resolve`, using the Swift toolchain Bazel is configured with.
For more examples, check `rules_swift_package_manager`'s [examples](https://github.com/cgrindel/rules_swift_package_manager/tree/main/examples)
### Step 3: Create a `BUILD` file
Once you have defined the workspace and external dependencies, you need to
create a `BUILD` file that tells Bazel how the project is structured. Create the
`BUILD` file at the root of the Bazel workspace and configure it to do an
initial build of the project as follows:
* [Step 3a: Add the application target](#step-3a-add-the-application-target)
* [Step 3b: (Optional) Add the test target(s)](#step-3b-optional-add-the-test-target-s)
* [Step 3c: Add the library target(s)](#step-3c-add-the-library-target-s)
**Tip:** To learn more about packages and other Bazel concepts, see [Workspaces, packages, and targets](/concepts/build-ref).
#### Step 3a: Add the application target
Add a
[`macos_application`](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-macos.md#macos_application)
or an
[`ios_application`](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-ios.md#ios_application)
rule target. This target builds a macOS or iOS application bundle, respectively.
In the target, specify the following at the minimum:
* `bundle_id` - the bundle ID (reverse-DNS path followed by app name) of the
binary.
* `provisioning_profile` - provisioning profile from your Apple Developer
account (if building for an iOS device).
* `families` (iOS only) - whether to build the application for iPhone, iPad,
or both.
* `infoplists` - list of .plist files to merge into the final Info.plist file.
* `minimum_os_version` - the minimum version of macOS or iOS that the
application supports. This ensures Bazel builds the application with the
correct API levels.
#### Step 3b: (Optional) Add the test target(s)
Bazel's [Apple build rules](https://github.com/bazelbuild/rules_apple) support running
unit and UI tests on all Apple platforms. Add test targets as follows:
* [`macos_unit_test`](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-macos.md#macos_unit_test)
to run library-based and application-based unit tests on a macOS.
* [`ios_unit_test`](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-ios.md#ios_unit_test)
to build and run library-based unit tests on iOS.
* [`ios_ui_test`](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-ios.md#ios_ui_test)
to build and run user interface tests in the iOS simulator.
* Similar test rules exist for
[tvOS](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-tvos.md),
[watchOS](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-watchos.md)
and
[visionOS](https://github.com/bazelbuild/rules_apple/blob/master/doc/rules-visionos.md).
At the minimum, specify a value for the `minimum_os_version` attribute. While
other packaging attributes, such as `bundle_identifier` and `infoplists`,
default to most commonly used values, ensure that those defaults are compatible
with the project and adjust them as necessary. For tests that require the iOS
simulator, also specify the `ios_application` target name as the value of the
`test_host` attribute.
#### Step 3c: Add the library target(s)
Add an [`objc_library`](/reference/be/objective-c#objc_library) target for each
Objective-C library and a
[`swift_library`](https://github.com/bazelbuild/rules_swift/blob/master/doc/rules.md#swift_library)
target for each Swift library on which the application and/or tests depend.
Add the library targets as follows:
* Add the application library targets as dependencies to the application
targets.
* Add the test library targets as dependencies to the test targets.
* List the implementation sources in the `srcs` attribute.
* List the headers in the `hdrs` attribute.
Note: You can use the [`glob`](/reference/be/functions#glob) function to include
all sources and/or headers of a certain type. Use it carefully as it might
include files you do not want Bazel to build.
You can browse existing examples for various types of applications directly in
the [rules\_apple examples directory](https://github.com/bazelbuild/rules_apple/tree/master/examples/). For
example:
* [macOS application targets](https://github.com/bazelbuild/rules_apple/tree/master/examples/macos)
* [iOS applications targets](https://github.com/bazelbuild/rules_apple/tree/master/examples/ios)
* [Multi platform applications (macOS, iOS, watchOS, tvOS)](https://github.com/bazelbuild/rules_apple/tree/master/examples/multi_platform)
For more information on build rules, see [Apple Rules for Bazel](https://github.com/bazelbuild/rules_apple).
At this point, it is a good idea to test the build:
`bazel build //:`
### Step 4: (Optional) Granularize the build
If the project is large, or as it grows, consider chunking it into multiple
Bazel packages. This increased granularity provides:
* Increased incrementality of builds,
* Increased parallelization of build tasks,
* Better maintainability for future users,
* Better control over source code visibility across targets and packages. This
prevents issues such as libraries containing implementation details leaking
into public APIs.
Tips for granularizing the project:
* Put each library in its own Bazel package. Start with those requiring the
fewest dependencies and work your way up the dependency tree.
* As you add `BUILD` files and specify targets, add these new targets to the
`deps` attributes of targets that depend on them.
* The `glob()` function does not cross package boundaries, so as the number of
packages grows the files matched by `glob()` will shrink.
* When adding a `BUILD` file to a `main` directory, also add a `BUILD` file to
the corresponding `test` directory.
* Enforce healthy visibility limits across packages.
* Build the project after each major change to the `BUILD` files and fix build
errors as you encounter them.
### Step 5: Run the build
Run the fully migrated build to ensure it completes with no errors or warnings.
Run every application and test target individually to more easily find sources
of any errors that occur.
For example:
```posix-terminal theme={null}
bazel build //:my-target
```
### Step 6: Generate the Xcode project with rules\_xcodeproj
When building with Bazel, the `MODULE.bazel` and `BUILD` files become the source
of truth about the build. To make Xcode aware of this, you must generate a
Bazel-compatible Xcode project using
[rules\_xcodeproj](https://github.com/buildbuddy-io/rules_xcodeproj#features)
.
### Troubleshooting
Bazel errors can arise when it gets out of sync with the selected Xcode version,
like when you apply an update. Here are some things to try if you're
experiencing errors with Xcode, for example "Xcode version must be specified to
use an Apple CROSSTOOL".
* Manually run Xcode and accept any terms and conditions.
* Use Xcode select to indicate the correct version, accept the license, and
clear Bazel's state.
```posix-terminal theme={null}
sudo xcode-select -s /Applications/Xcode.app/Contents/Developer
sudo xcodebuild -license
bazel sync --configure
```
* If this does not work, you may also try running `bazel clean --expunge`.
Note: If you've saved your Xcode to a different path, you can use `xcode-select
-s` to point to that path.
# Query guide
Source: https://bazel.build/query/guide
This page covers how to get started using Bazel's query language to trace
dependencies in your code.
For a language details and `--output` flag details, please see the
reference manuals, [Bazel query reference](/query/language)
and [Bazel cquery reference](/query/cquery). You can get help by
typing `bazel help query` or `bazel help cquery` on the
command line.
To execute a query while ignoring errors such as missing targets, use the
`--keep_going` flag.
## Finding the dependencies of a rule
To see the dependencies of `//foo`, use the
`deps` function in bazel query:
```
$ bazel query "deps(//foo)"
//foo:foo
//foo:foo-dep
...
```
This is the set of all targets required to build `//foo`.
## Tracing the dependency chain between two packages
The library `//third_party/zlib:zlibonly` isn't in the BUILD file for
`//foo`, but it is an indirect dependency. How can
we trace this dependency path? There are two useful functions here:
`allpaths` and `somepath`. You may also want to exclude
tooling dependencies with `--notool_deps` if you care only about
what is included in the artifact you built, and not every possible job.
To visualize the graph of all dependencies, pipe the bazel query output through
the `dot` command-line tool:
```
$ bazel query "allpaths(//foo, third_party/...)" --notool_deps --output graph | dot -Tsvg > /tmp/deps.svg
```
Note: `dot` supports other image formats, just replace `svg` with the
format identifier, for example, `png`.
When a dependency graph is big and complicated, it can be helpful start with a single path:
```
$ bazel query "somepath(//foo:foo, third_party/zlib:zlibonly)"
//foo:foo
//translations/tools:translator
//translations/base:base
//third_party/py/MySQL:MySQL
//third_party/py/MySQL:_MySQL.so
//third_party/mysql:mysql
//third_party/zlib:zlibonly
```
If you do not specify `--output graph` with `allpaths`,
you will get a flattened list of the dependency graph.
```
$ bazel query "allpaths(//foo, third_party/...)"
...many errors detected in BUILD files...
//foo:foo
//translations/tools:translator
//translations/tools:aggregator
//translations/base:base
//tools/pkg:pex
//tools/pkg:pex_phase_one
//tools/pkg:pex_lib
//third_party/python:python_lib
//translations/tools:messages
//third_party/py/xml:xml
//third_party/py/xml:utils/boolean.so
//third_party/py/xml:parsers/sgmlop.so
//third_party/py/xml:parsers/pyexpat.so
//third_party/py/MySQL:MySQL
//third_party/py/MySQL:_MySQL.so
//third_party/mysql:mysql
//third_party/openssl:openssl
//third_party/zlib:zlibonly
//third_party/zlib:zlibonly_v1_2_3
//third_party/python:headers
//third_party/openssl:crypto
```
### Aside: implicit dependencies
The BUILD file for `//foo` never references
`//translations/tools:aggregator`. So, where's the direct dependency?
Certain rules include implicit dependencies on additional libraries or tools.
For example, to build a `genproto` rule, you need first to build the Protocol
Compiler, so every `genproto` rule carries an implicit dependency on the
protocol compiler. These dependencies are not mentioned in the build file,
but added in by the build tool. The full set of implicit dependencies is
currently undocumented. Using `--noimplicit_deps` allows you to filter out
these deps from your query results. For cquery, this will include resolved toolchains.
## Reverse dependencies
You might want to know the set of targets that depends on some target. For instance,
if you're going to change some code, you might want to know what other code
you're about to break. You can use `rdeps(u, x)` to find the reverse
dependencies of the targets in `x` within the transitive closure of `u`.
Bazel's [Sky Query](/query/language#sky-query)
supports the `allrdeps` function which allows you to query reverse dependencies
in a universe you specify.
## Miscellaneous uses
You can use `bazel query` to analyze many dependency relationships.
### What exists ...
#### What packages exist beneath `foo`?
```
bazel query 'foo/...' --output package
```
#### What rules are defined in the `foo` package?
```
bazel query 'kind(rule, foo:*)' --output label_kind
```
#### What files are generated by rules in the `foo` package?
```
bazel query 'kind("generated file", //foo:*)'
```
#### What targets are generated by starlark macro `foo`?
```
bazel query 'attr(generator_function, foo, //path/to/search/...)'
```
#### What's the set of BUILD files needed to build `//foo`?
```
bazel query 'buildfiles(deps(//foo))' | cut -f1 -d:
```
#### What are the individual tests that a `test_suite` expands to?
```
bazel query 'tests(//foo:smoke_tests)'
```
#### Which of those are C++ tests?
```
bazel query 'kind(cc_.*, tests(//foo:smoke_tests))'
```
#### Which of those are small? Medium? Large?
```
bazel query 'attr(size, small, tests(//foo:smoke_tests))'
bazel query 'attr(size, medium, tests(//foo:smoke_tests))'
bazel query 'attr(size, large, tests(//foo:smoke_tests))'
```
#### What are the tests beneath `foo` that match a pattern?
```
bazel query 'filter("pa?t", kind(".*_test rule", //foo/...))'
```
The pattern is a regex and is applied to the full name of the rule. It's similar to doing
```
bazel query 'kind(".*_test rule", //foo/...)' | grep -E 'pa?t'
```
#### What package contains file `path/to/file/bar.java`?
```
bazel query path/to/file/bar.java --output=package
```
#### What is the build label for `path/to/file/bar.java?`
```
bazel query path/to/file/bar.java
```
#### What rule target(s) contain file `path/to/file/bar.java` as a source?
```
fullname=$(bazel query path/to/file/bar.java)
bazel query "attr('srcs', $fullname, ${fullname//:*/}:*)"
```
### What package dependencies exist ...
#### What packages does `foo` depend on? (What do I need to check out to build `foo`)
```
bazel query 'buildfiles(deps(//foo:foo))' --output package
```
Note: `buildfiles` is required in order to correctly obtain all files
referenced by `subinclude`; see the reference manual for details.
#### What packages does the `foo` tree depend on, excluding `foo/contrib`?
```
bazel query 'deps(foo/... except foo/contrib/...)' --output package
```
### What rule dependencies exist ...
#### What genproto rules does bar depend upon?
```
bazel query 'kind(genproto, deps(bar/...))'
```
#### Find the definition of some JNI (C++) library that is transitively depended upon by a Java binary rule in the servlet tree.
```
bazel query 'some(kind(cc_.*library, deps(kind(java_binary, //java/com/example/frontend/...))))' --output location
```
##### ...Now find the definitions of all the Java binaries that depend on them
```
bazel query 'let jbs = kind(java_binary, //java/com/example/frontend/...) in
let cls = kind(cc_.*library, deps($jbs)) in
$jbs intersect allpaths($jbs, $cls)'
```
### What file dependencies exist ...
#### What's the complete set of Java source files required to build foo?
Source files:
```
bazel query 'kind("source file", deps(//path/to/target/foo/...))' | grep java$
```
Generated files:
```
bazel query 'kind("generated file", deps(//path/to/target/foo/...))' | grep java$
```
#### What is the complete set of Java source files required to build QUX's tests?
Source files:
```
bazel query 'kind("source file", deps(kind(".*_test rule", javatests/com/example/qux/...)))' | grep java$
```
Generated files:
```
bazel query 'kind("generated file", deps(kind(".*_test rule", javatests/com/example/qux/...)))' | grep java$
```
### What differences in dependencies between X and Y exist ...
#### What targets does `//foo` depend on that `//foo:foolib` does not?
```
bazel query 'deps(//foo) except deps(//foo:foolib)'
```
#### What C++ libraries do the `foo` tests depend on that the `//foo` production binary does *not* depend on?
```
bazel query 'kind("cc_library", deps(kind(".*test rule", foo/...)) except deps(//foo))'
```
### Why does this dependency exist ...
#### Why does `bar` depend on `groups2`?
```
bazel query 'somepath(bar/...,groups2/...:*)'
```
Once you have the results of this query, you will often find that a single
target stands out as being an unexpected or egregious and undesirable
dependency of `bar`. The query can then be further refined to:
#### Show me a path from `docker/updater:updater_systest` (a `py_test`) to some `cc_library` that it depends upon:
```
bazel query 'let cc = kind(cc_library, deps(docker/updater:updater_systest)) in
somepath(docker/updater:updater_systest, $cc)'
```
#### Why does library `//photos/frontend:lib` depend on two variants of the same library `//third_party/jpeglib` and `//third_party/jpeg`?
This query boils down to: "show me the subgraph of `//photos/frontend:lib` that
depends on both libraries". When shown in topological order, the last element
of the result is the most likely culprit.
```
bazel query 'allpaths(//photos/frontend:lib, //third_party/jpeglib)
intersect
allpaths(//photos/frontend:lib, //third_party/jpeg)'
//photos/frontend:lib
//photos/frontend:lib_impl
//photos/frontend:lib_dispatcher
//photos/frontend:icons
//photos/frontend/modules/gadgets:gadget_icon
//photos/thumbnailer:thumbnail_lib
//third_party/jpeg/img:renderer
```
### What depends on ...
#### What rules under bar depend on Y?
```
bazel query 'bar/... intersect allpaths(bar/..., Y)'
```
Note: `X intersect allpaths(X, Y)` is the general idiom for the query "which X
depend on Y?" If expression X is non-trivial, it may be convenient to bind a
name to it using `let` to avoid duplication.
#### What targets directly depend on T, in T's package?
```
bazel query 'same_pkg_direct_rdeps(T)'
```
### How do I break a dependency ...
#### What dependency paths do I have to break to make `bar` no longer depend on X?
To output the graph to a `svg` file:
```
bazel query 'allpaths(bar/...,X)' --output graph | dot -Tsvg > /tmp/dep.svg
```
### Misc
#### How many sequential steps are there in the `//foo-tests` build?
Unfortunately, the query language can't currently give you the longest path
from x to y, but it can find the (or rather *a*) most distant node from the
starting point, or show you the *lengths* of the longest path from x to every
y that it depends on. Use `maxrank`:
```
bazel query 'deps(//foo-tests)' --output maxrank | tail -1
85 //third_party/zlib:zutil.c
```
The result indicates that there exist paths of length 85 that must occur in
order in this build.
# The Bazel Query Reference
Source: https://bazel.build/query/language
This page is the reference manual for the *Bazel Query Language* used
when you use `bazel query` to analyze build dependencies. It also
describes the output formats `bazel query` supports.
For practical use cases, see the [Bazel Query How-To](/query/guide).
## Additional query reference
In addition to `query`, which runs on the post-loading phase target graph,
Bazel includes *action graph query* and *configurable query*.
### Action graph query
The action graph query (`aquery`) operates on the post-analysis Configured
Target Graph and exposes information about **Actions**, **Artifacts**, and
their relationships. `aquery` is useful when you are interested in the
properties of the Actions/Artifacts generated from the Configured Target Graph.
For example, the actual commands run and their inputs, outputs, and mnemonics.
For more details, see the [aquery reference](/query/aquery).
### Configurable query
Traditional Bazel query runs on the post-loading phase target graph and
therefore has no concept of configurations and their related concepts. Notably,
it doesn't correctly resolve [select statements](/reference/be/functions#select)
and instead returns all possible resolutions of selects. However, the
configurable query environment, `cquery`, properly handles configurations but
doesn't provide all of the functionality of this original query.
For more details, see the [cquery reference](/query/cquery).
## Examples
How do people use `bazel query`? Here are typical examples:
Why does the `//foo` tree depend on `//bar/baz`?
Show a path:
```
somepath(foo/..., //bar/baz:all)
```
What C++ libraries do all the `foo` tests depend on that
the `foo_bin` target does not?
```
kind("cc_library", deps(kind(".*test rule", foo/...)) except deps(//foo:foo_bin))
```
## Tokens: The lexical syntax
Expressions in the query language are composed of the following
tokens:
* **Keywords**, such as `let`. Keywords are the reserved words of the
language, and each of them is described below. The complete set
of keywords is:
* [`except`](#set-operations)
* [`in`](#variables)
* [`intersect`](#set-operations)
* [`let`](#variables)
* [`set`](#set)
* [`union`](#set-operations)
* **Words**, such as "`foo/...`" or "`.*test rule`" or "`//bar/baz:all`". If a
character sequence is "quoted" (begins and ends with a single-quote ' or
begins and ends with a double-quote "), it is a word. If a character sequence
is not quoted, it may still be parsed as a word. Unquoted words are sequences
of characters drawn from the alphabet characters A-Za-z, the numerals 0-9,
and the special characters `*/@.-_:$~[]` (asterisk, forward slash, at, period,
hyphen, underscore, colon, dollar sign, tilde, left square brace, right square
brace). However, unquoted words may not start with a hyphen `-` or asterisk `*`
even though relative [target names](/concepts/labels#target-names) may start
with those characters. As a special rule meant to simplify the handling of
labels referring to external repositories, unquoted words that start with
`@@` may contain `+` characters.
Unquoted words also may not include the characters plus sign `+` or equals
sign `=`, even though those characters are permitted in target names. When
writing code that generates query expressions, target names should be quoted.
Quoting *is* necessary when writing scripts that construct Bazel query
expressions from user-supplied values.
```
//foo:bar+wiz # WRONG: scanned as //foo:bar + wiz.
//foo:bar=wiz # WRONG: scanned as //foo:bar = wiz.
"//foo:bar+wiz" # OK.
"//foo:bar=wiz" # OK.
```
Note that this quoting is in addition to any quoting that may be required by
your shell, such as:
```posix-terminal theme={null}
bazel query ' "//foo:bar=wiz" ' # single-quotes for shell, double-quotes for Bazel.
```
Keywords and operators, when quoted, are treated as ordinary words. For example, `some` is a
keyword but "some" is a word. Both `foo` and "foo" are words.
However, be careful when using single or double quotes in target names. When
quoting one or more target names, use only one type of quotes (either all
single or all double quotes).
The following are examples of what the Java query string will be:
```
'a"'a' # WRONG: Error message: unclosed quotation.
"a'"a" # WRONG: Error message: unclosed quotation.
'"a" + 'a'' # WRONG: Error message: unexpected token 'a' after query expression '"a" + '
"'a' + "a"" # WRONG: Error message: unexpected token 'a' after query expression ''a' + '
"a'a" # OK.
'a"a' # OK.
'"a" + "a"' # OK
"'a' + 'a'" # OK
```
We chose this syntax so that quote marks aren't needed in most cases. The
(unusual) `".*test rule"` example needs quotes: it starts with a period and
contains a space. Quoting `"cc_library"` is unnecessary but harmless.
* **Punctuation**, such as parens `()`, period `.` and comma `,`. Words
containing punctuation (other than the exceptions listed above) must be quoted.
Whitespace characters outside of a quoted word are ignored.
## Bazel query language concepts
The Bazel query language is a language of expressions. Every
expression evaluates to a **partially-ordered set** of targets,
or equivalently, a **graph** (DAG) of targets. This is the only
datatype.
Set and graph refer to the same datatype, but emphasize different
aspects of it, for example:
* **Set:** The partial order of the targets is not interesting.
* **Graph:** The partial order of targets is significant.
### Cycles in the dependency graph
Build dependency graphs should be acyclic.
The algorithms used by the query language are robust against cycles, and will
not report cycles as errors.
Note that the post-loading phase unconfigured target graph that `bazel query`
operates over may contain cycles that do not exist in the configured target
graph. Cycles in the configured target graph are detected and reported as errors
by [`bazel cquery`](/query/cquery) and [`bazel aquery`](/query/aquery).
### Implicit dependencies
In addition to build dependencies that are defined explicitly in `BUILD` files,
Bazel adds additional *implicit* dependencies to rules. Implicit dependencies
may be defined by:
* [Private attributes](/extending/rules#private_attributes_and_implicit_dependencies)
* [Toolchain requirements](/extending/toolchains#writing-rules-toolchains)
By default, `bazel query` takes implicit dependencies into account
when computing the query result. This behavior can be changed with
the `--[no]implicit_deps` option.
Note that, as query does not consider configurations, potential toolchain
**implementations** are not considered dependencies, only the
required toolchain types. See
[toolchain documentation](/extending/toolchains#writing-rules-toolchains).
### Soundness
Bazel query language expressions operate over the build
dependency graph, which is the graph implicitly defined by all
rule declarations in all `BUILD` files. It is important to understand
that this graph is somewhat abstract, and does not constitute a
complete description of how to perform all the steps of a build. In
order to perform a build, a *configuration* is required too;
see the [configurations](/docs/user-manual#configurations)
section of the User's Guide for more detail.
The result of evaluating an expression in the Bazel query language
is true *for all configurations*, which means that it may be
a conservative over-approximation, and not exactly precise. If you
use the query tool to compute the set of all source files needed
during a build, it may report more than are actually necessary
because, for example, the query tool will include all the files
needed to support message translation, even though you don't intend
to use that feature in your build.
### On the preservation of graph order
Operations preserve any ordering
constraints inherited from their subexpressions. You can think of
this as "the law of conservation of partial order". Consider an
example: if you issue a query to determine the transitive closure of
dependencies of a particular target, the resulting set is ordered
according to the dependency graph. If you filter that set to
include only the targets of `file` kind, the same
*transitive* partial ordering relation holds between every
pair of targets in the resulting subset - even though none of
these pairs is actually directly connected in the original graph.
(There are no file-file edges in the build dependency graph).
However, while all operators *preserve* order, some
operations, such as the [set operations](#set-operations)
don't *introduce* any ordering constraints of their own.
Consider this expression:
```
deps(x) union y
```
The order of the final result set is guaranteed to preserve all the
ordering constraints of its subexpressions, namely, that all the
transitive dependencies of `x` are correctly ordered with
respect to each other. However, the query guarantees nothing about
the ordering of the targets in `y`, nor about the
ordering of the targets in `deps(x)` relative to those in
`y` (except for those targets in
`y` that also happen to be in `deps(x)`).
Operators that introduce ordering constraints include:
`allpaths`, `deps`, `rdeps`, `somepath`, and the target pattern wildcards
`package:*`, `dir/...`, etc.
### Sky query
*Sky Query* is a mode of query that operates over a specified *universe scope*.
#### Special functions available only in SkyQuery
Sky Query mode has the additional query functions `allrdeps` and
`rbuildfiles`. These functions operate over the entire
universe scope (which is why they don't make sense for normal Query).
#### Specifying a universe scope
Sky Query mode is activated by passing the following two flags:
(`--universe_scope` or `--infer_universe_scope`) and
`--order_output=no`.
`--universe_scope=,...,` tells query to
preload the transitive closure of the target pattern specified by the target patterns, which can
be both additive and subtractive. All queries are then evaluated in this "scope". In particular,
the [`allrdeps`](#allrdeps) and
[`rbuildfiles`](#rbuildfiles) operators only return results from this scope.
`--infer_universe_scope` tells Bazel to infer a value for `--universe_scope`
from the query expression. This inferred value is the list of unique target patterns in the
query expression, but this might not be what you want. For example:
```posix-terminal theme={null}
bazel query --infer_universe_scope --order_output=no "allrdeps(//my:target)"
```
The list of unique target patterns in this query expression is `["//my:target"]`, so
Bazel treats this the same as the invocation:
```posix-terminal theme={null}
bazel query --universe_scope=//my:target --order_output=no "allrdeps(//my:target)"
```
But the result of that query with `--universe_scope` is only `//my:target`;
none of the reverse dependencies of `//my:target` are in the universe, by
construction! On the other hand, consider:
```posix-terminal theme={null}
bazel query --infer_universe_scope --order_output=no "tests(//a/... + b/...) intersect allrdeps(siblings(rbuildfiles(my/starlark/file.bzl)))"
```
This is a meaningful query invocation that is trying to compute the test targets in the
[`tests`](#tests) expansion of the targets under some directories that
transitively depend on targets whose definition uses a certain `.bzl` file. Here,
`--infer_universe_scope` is a convenience, especially in the case where the choice of
`--universe_scope` would otherwise require you to parse the query expression yourself.
So, for query expressions that use universe-scoped operators like
[`allrdeps`](#allrdeps) and
[`rbuildfiles`](#rbuildfiles) be sure to use
`--infer_universe_scope` only if its behavior is what you want.
Sky Query has some advantages and disadvantages compared to the default query. The main
disadvantage is that it cannot order its output according to graph order, and thus certain
[output formats](#output-formats) are forbidden. Its advantages are that it provides
two operators ([`allrdeps`](#allrdeps) and
[`rbuildfiles`](#rbuildfiles)) that are not available in the default query.
As well, Sky Query does its work by introspecting the
[Skyframe](/reference/skyframe) graph, rather than creating a new
graph, which is what the default implementation does. Thus, there are some circumstances in which
it is faster and uses less memory.
## Expressions: Syntax and semantics of the grammar
This is the grammar of the Bazel query language, expressed in EBNF notation:
```none theme={null}
expr ::= word
| let name = expr in expr
| (expr)
| expr intersect expr
| expr ^ expr
| expr union expr
| expr + expr
| expr except expr
| expr - expr
| set(word *)
| word '(' int | word | expr ... ')'
```
The following sections describe each of the productions of this grammar in order.
### Target patterns
```
expr ::= word
```
Syntactically, a *target pattern* is just a word. It's interpreted as an
(unordered) set of targets. The simplest target pattern is a label, which
identifies a single target (file or rule). For example, the target pattern
`//foo:bar` evaluates to a set containing one element, the target, the `bar`
rule.
Target patterns generalize labels to include wildcards over packages and
targets. For example, `foo/...:all` (or just `foo/...`) is a target pattern
that evaluates to a set containing all *rules* in every package recursively
beneath the `foo` directory; `bar/baz:all` is a target pattern that evaluates
to a set containing all the rules in the `bar/baz` package, but not its
subpackages.
Similarly, `foo/...:*` is a target pattern that evaluates to a set containing
all *targets* (rules *and* files) in every package recursively beneath the
`foo` directory; `bar/baz:*` evaluates to a set containing all the targets in
the `bar/baz` package, but not its subpackages.
Because the `:*` wildcard matches files as well as rules, it's often more
useful than `:all` for queries. Conversely, the `:all` wildcard (implicit in
target patterns like `foo/...`) is typically more useful for builds.
`bazel query` target patterns work the same as `bazel build` build targets do.
For more details, see [Target Patterns](/docs/user-manual#target-patterns), or
type `bazel help target-syntax`.
Target patterns may evaluate to a singleton set (in the case of a label), to a
set containing many elements (as in the case of `foo/...`, which has thousands
of elements) or to the empty set, if the target pattern matches no targets.
All nodes in the result of a target pattern expression are correctly ordered
relative to each other according to the dependency relation. So, the result of
`foo:*` is not just the set of targets in package `foo`, it is also the
*graph* over those targets. (No guarantees are made about the relative ordering
of the result nodes against other nodes.) For more details, see the
[graph order](#graph-order) section.
### Variables
```none theme={null}
expr ::= let name = expr{{ '' }}1{{ '' }} in expr{{ '' }}2{{ '' }}
| $name
```
The Bazel query language allows definitions of and references to
variables. The result of evaluation of a `let` expression is the same as
that of expr2, with all free occurrences
of variable name replaced by the value of
expr1.
For example, `let v = foo/... in allpaths($v, //common) intersect $v` is
equivalent to the `allpaths(foo/...,//common) intersect foo/...`.
An occurrence of a variable reference `name` other than in
an enclosing `let name = ...` expression is an
error. In other words, top-level query expressions cannot have free
variables.
In the above grammar productions, `name` is like *word*, but with the
additional constraint that it be a legal identifier in the C programming
language. References to the variable must be prepended with the "\$" character.
Each `let` expression defines only a single variable, but you can nest them.
Both [target patterns](#target-patterns) and variable references consist of
just a single token, a word, creating a syntactic ambiguity. However, there is
no semantic ambiguity, because the subset of words that are legal variable
names is disjoint from the subset of words that are legal target patterns.
Technically speaking, `let` expressions do not increase
the expressiveness of the query language: any query expressible in
the language can also be expressed without them. However, they
improve the conciseness of many queries, and may also lead to more
efficient query evaluation.
### Parenthesized expressions
```none theme={null}
expr ::= (expr)
```
Parentheses associate subexpressions to force an order of evaluation.
A parenthesized expression evaluates to the value of its argument.
### Algebraic set operations: intersection, union, set difference
```none theme={null}
expr ::= expr intersect expr
| expr ^ expr
| expr union expr
| expr + expr
| expr except expr
| expr - expr
```
These three operators compute the usual set operations over their arguments.
Each operator has two forms, a nominal form, such as `intersect`, and a
symbolic form, such as `^`. Both forms are equivalent; the symbolic forms are
quicker to type. (For clarity, the rest of this page uses the nominal forms.)
For example,
```
foo/... except foo/bar/...
```
evaluates to the set of targets that match `foo/...` but not `foo/bar/...`.
You can write the same query as:
```
foo/... - foo/bar/...
```
The `intersect` (`^`) and `union` (`+`) operations are commutative (symmetric);
`except` (`-`) is asymmetric. The parser treats all three operators as
left-associative and of equal precedence, so you might want parentheses. For
example, the first two of these expressions are equivalent, but the third is not:
```
x intersect y union z
(x intersect y) union z
x intersect (y union z)
```
Important: Use parentheses where there is any danger of ambiguity in reading a
query expression.
### Read targets from an external source: set
```none theme={null}
expr ::= set(word *)
```
The `set(abc ...)`
operator computes the union of a set of zero or more
[target patterns](#target-patterns), separated by whitespace (no commas).
In conjunction with the Bourne shell's `$(...)` feature, `set()` provides a
means of saving the results of one query in a regular text file, manipulating
that text file using other programs (such as standard UNIX shell tools), and then
introducing the result back into the query tool as a value for further
processing. For example:
```posix-terminal theme={null}
bazel query deps(//my:target) --output=label | grep ... | sed ... | awk ... > foo
bazel query "kind(cc_binary, set($( foo
bazel query "kind(cc_library, set($(word '(' int | word | expr ... ')'
```
The query language defines several functions. The name of the function
determines the number and type of arguments it requires. The following
functions are available:
* [`allpaths`](#somepath-allpaths)
* [`attr`](#attr)
* [`buildfiles`](#buildfiles)
* [`rbuildfiles`](#rbuildfiles)
* [`deps`](#deps)
* [`executables`](#executables)
* [`filter`](#filter)
* [`kind`](#kind)
* [`labels`](#labels)
* [`loadfiles`](#loadfiles)
* [`rdeps`](#rdeps)
* [`allrdeps`](#allrdeps)
* [`same_pkg_direct_rdeps`](#same_pkg_direct_rdeps)
* [`siblings`](#siblings)
* [`some`](#some)
* [`somepath`](#somepath-allpaths)
* [`tests`](#tests)
* [`visible`](#visible)
### Transitive closure of dependencies: deps
```none theme={null}
expr ::= deps(expr)
| deps(expr, depth)
```
The `deps(x)` operator evaluates to the graph formed
by the transitive closure of dependencies of its argument set
x. For example, the value of `deps(//foo)` is the
dependency graph rooted at the single node `foo`, including all its
dependencies. The value of `deps(foo/...)` is the dependency graphs whose roots
are all rules in every package beneath the `foo` directory. In this context,
'dependencies' means only rule and file targets, therefore the `BUILD` and
Starlark files needed to create these targets are not included here. For that
you should use the [`buildfiles`](#buildfiles) operator.
The resulting graph is ordered according to the dependency relation. For more
details, see the section on [graph order](#graph-order).
The `deps` operator accepts an optional second argument, which is an integer
literal specifying an upper bound on the depth of the search. So
`deps(foo:*, 0)` returns all targets in the `foo` package, while
`deps(foo:*, 1)` further includes the direct prerequisites of any target in the
`foo` package, and `deps(foo:*, 2)` further includes the nodes directly
reachable from the nodes in `deps(foo:*, 1)`, and so on. (These numbers
correspond to the ranks shown in the [`minrank`](#output-ranked) output format.)
If the depth parameter is omitted, the search is
unbounded: it computes the reflexive transitive closure of prerequisites.
### Transitive closure of reverse dependencies: rdeps
```none theme={null}
expr ::= rdeps(expr, expr)
| rdeps(expr, expr, depth)
```
The `rdeps(u, x)`
operator evaluates to the reverse dependencies of the argument set
x within the transitive closure of the universe set
u.
The resulting graph is ordered according to the dependency relation. See the
section on [graph order](#graph-order) for more details.
The `rdeps` operator accepts an optional third argument, which is an integer
literal specifying an upper bound on the depth of the search. The resulting
graph only includes nodes within a distance of the specified depth from any
node in the argument set. So `rdeps(//foo, //common, 1)` evaluates to all nodes
in the transitive closure of `//foo` that directly depend on `//common`. (These
numbers correspond to the ranks shown in the [`minrank`](#output-ranked) output
format.) If the depth parameter is omitted, the
search is unbounded.
### Transitive closure of all reverse dependencies: allrdeps
```
expr ::= allrdeps(expr)
| allrdeps(expr, depth)
```
Note: Only available with [Sky Query](#sky-query)
The `allrdeps` operator behaves just like the [`rdeps`](#rdeps)
operator, except that the "universe set" is whatever the `--universe_scope` flag
evaluated to, instead of being separately specified. Thus, if
`--universe_scope=//foo/...` was passed, then `allrdeps(//bar)` is
equivalent to `rdeps(//foo/..., //bar)`.
### Direct reverse dependencies in the same package: same\_pkg\_direct\_rdeps
```
expr ::= same_pkg_direct_rdeps(expr)
```
The `same_pkg_direct_rdeps(x)` operator evaluates to the full set of targets
that are in the same package as a target in the argument set, and which directly depend on it.
### Dealing with a target's package: siblings
```
expr ::= siblings(expr)
```
The `siblings(x)` operator evaluates to the full set of targets that are in
the same package as a target in the argument set.
### Arbitrary choice: some
```
expr ::= some(expr)
| some(expr, count{{ ' '}})
```
The `some(x, k)` operator
selects at most k targets arbitrarily from its
argument set x, and evaluates to a set containing
only those targets. Parameter k is optional; if
missing, the result will be a singleton set containing only one target
arbitrarily selected. If the size of argument set x is
smaller than k, the whole argument set
x will be returned.
For example, the expression `some(//foo:main union //bar:baz)` evaluates to a
singleton set containing either `//foo:main` or `//bar:baz`—though which
one is not defined. The expression `some(//foo:main union //bar:baz, 2)` or
`some(//foo:main union //bar:baz, 3)` returns both `//foo:main` and
`//bar:baz`.
If the argument is a singleton, then `some`
computes the identity function: `some(//foo:main)` is
equivalent to `//foo:main`.
It is an error if the specified argument set is empty, as in the
expression `some(//foo:main intersect //bar:baz)`.
### Path operators: somepath, allpaths
```
expr ::= somepath(expr, expr)
| allpaths(expr, expr)
```
The `somepath(S, E)` and
`allpaths(S, E)` operators compute
paths between two sets of targets. Both queries accept two
arguments, a set S of starting points and a set
E of ending points. `somepath` returns the
graph of nodes on *some* arbitrary path from a target in
S to a target in E; `allpaths`
returns the graph of nodes on *all* paths from any target in
S to any target in E.
The resulting graphs are ordered according to the dependency relation.
See the section on [graph order](#graph-order) for more details.
somepath(S1 + S2, E), one possible result.
somepath(S1 + S2, E), another possible result.
allpaths(S1 + S2, E)
### Target kind filtering: kind
```
expr ::= kind(word, expr)
```
The `kind(pattern, input)`
operator applies a filter to a set of targets, and discards those targets
that are not of the expected kind. The pattern
parameter specifies what kind of target to match.
For example, the kinds for the four targets defined by the `BUILD` file
(for package `p`) shown below are illustrated in the table:
```starlark theme={null}
genrule(
name = "a",
srcs = ["a.in"],
outs = ["a.out"],
cmd = "...",
)
```
This `BUILD` file defines four targets:
* `//p:a` — a `genrule` rule
* `//p:a.in` — a source file
* `//p:a.out` — a generated file
* `//p:BUILD` — a source file
Thus, `kind("cc_.* rule", foo/...)` evaluates to the set
of all `cc_library`, `cc_binary`, etc,
rule targets beneath `foo`, and `kind("source file", deps(//foo))`
evaluates to the set of all source files in the transitive closure
of dependencies of the `//foo` target.
Quotation of the pattern argument is often required
because without it, many [regular expressions](#regex), such as `source
file` and `.*_test`, are not considered words by the parser.
When matching for `package group`, targets ending in
`:all` may not yield any results. Use `:all-targets` instead.
### Target name filtering: filter
```
expr ::= filter(word, expr)
```
The `filter(pattern, input)`
operator applies a filter to a set of targets, and discards targets whose
labels (in absolute form) do not match the pattern; it
evaluates to a subset of its input.
The first argument, pattern is a word containing a
[regular expression](#regex) over target names. A `filter` expression
evaluates to the set containing all targets x such that
x is a member of the set input and the
label (in absolute form, such as `//foo:bar`)
of x contains an (unanchored) match
for the regular expression pattern. Since all
target names start with `//`, it may be used as an alternative
to the `^` regular expression anchor.
This operator often provides a much faster and more robust alternative to the
`intersect` operator. For example, in order to see all
`bar` dependencies of the `//foo:foo` target, one could
evaluate
```
deps(//foo) intersect //bar/...
```
This statement, however, will require parsing of all `BUILD` files in the
`bar` tree, which will be slow and prone to errors in
irrelevant `BUILD` files. An alternative would be:
```
filter(//bar, deps(//foo))
```
which would first calculate the set of `//foo` dependencies and
then would filter only targets matching the provided pattern—in other
words, targets with names containing `//bar` as a substring.
Another common use of the `filter(pattern, expr)` operator is to filter specific files by their
name or extension. For example,
```
filter("\.cc$", deps(//foo))
```
will provide a list of all `.cc` files used to build `//foo`.
### Rule attribute filtering: attr
```
expr ::= attr(word, word, expr)
```
The
`attr(name, pattern, input)`
operator applies a filter to a set of targets, and discards targets that aren't
rules, rule targets that do not have attribute name
defined or rule targets where the attribute value does not match the provided
[regular expression](#regex) pattern; it evaluates
to a subset of its input.
The first argument, name is the name of the rule
attribute that should be matched against the provided
[regular expression](#regex) pattern. The second argument,
pattern is a regular expression over the attribute
values. An `attr` expression evaluates to the set containing all targets
x such that x is a
member of the set input, is a rule with the defined
attribute name and the attribute value contains an
(unanchored) match for the regular expression
pattern. If name is an
optional attribute and rule does not specify it explicitly then default
attribute value will be used for comparison. For example,
```
attr(linkshared, 0, deps(//foo))
```
will select all `//foo` dependencies that are allowed to have a
linkshared attribute (such as, `cc_binary` rule) and have it either
explicitly set to 0 or do not set it at all but default value is 0 (such as for
`cc_binary` rules).
List-type attributes (such as `srcs`, `data`, etc) are
converted to strings of the form `[value1, ..., valuen]`,
starting with a `[` bracket, ending with a `]` bracket
and using "`, `" (comma, space) to delimit multiple values.
Labels are converted to strings by using the absolute form of the
label. For example, an attribute `deps=[":foo",
"//otherpkg:bar", "wiz"]` would be converted to the
string `[//thispkg:foo, //otherpkg:bar, //thispkg:wiz]`.
Brackets are always present, so the empty list would use string value `[]`
for matching purposes. For example,
```
attr("srcs", "\[\]", deps(//foo))
```
will select all rules among `//foo` dependencies that have an
empty `srcs` attribute, while
```
attr("data", ".{3,}", deps(//foo))
```
will select all rules among `//foo` dependencies that specify at
least one value in the `data` attribute (every label is at least
3 characters long due to the `//` and `:`).
To select all rules among `//foo` dependencies with a particular `value` in a
list-type attribute, use
```
attr("tags", "[\[ ]value[,\]]", deps(//foo))
```
This works because the character before `value` will be `[` or a space and the
character after `value` will be a comma or `]`.
To select all rules among `//foo` dependencies with a particular `key` and
`value` in a dict-type attribute, use
```
attr("some_dict_attribute", "[\{ ]key=value[,\}]", deps(//foo))
```
This would select `//foo` if `//foo` is defined as
```
some_rule(
name = "foo",
some_dict_attribute = {
"key": "value",
},
)
```
This works because the character before `key=value` will be `{` or a space and
the character after `key=value` will be a comma or `}`.
### Rule visibility filtering: visible
```
expr ::= visible(expr, expr)
```
The `visible(predicate, input)` operator
applies a filter to a set of targets, and discards targets without the
required visibility.
The first argument, predicate, is a set of targets that all targets
in the output must be visible to. A visible expression
evaluates to the set containing all targets x such that x
is a member of the set input, and for all targets y in
predicatex is visible to y. For example:
```
visible(//foo, //bar:*)
```
will select all targets in the package `//bar` that `//foo`
can depend on without violating visibility restrictions.
### Evaluation of rule attributes of type label: labels
```
expr ::= labels(word, expr)
```
The `labels(attr_name, inputs)`
operator returns the set of targets specified in the
attribute attr\_name of type "label" or "list of label" in
some rule in set inputs.
For example, `labels(srcs, //foo)` returns the set of
targets appearing in the `srcs` attribute of
the `//foo` rule. If there are multiple rules
with `srcs` attributes in the inputs set, the
union of their `srcs` is returned.
### Expand and filter test\_suites: tests
```
expr ::= tests(expr)
```
The `tests(x)` operator returns the set of all test
rules in set x, expanding any `test_suite` rules into
the set of individual tests that they refer to, and applying filtering by
`tag` and `size`.
By default, query evaluation
ignores any non-test targets in all `test_suite` rules. This can be
changed to errors with the `--strict_test_suite` option.
For example, the query `kind(test, foo:*)` lists all
the `*_test` and `test_suite` rules
in the `foo` package. All the results are (by
definition) members of the `foo` package. In contrast,
the query `tests(foo:*)` will return all of the
individual tests that would be executed by `bazel test
foo:*`: this may include tests belonging to other packages,
that are referenced directly or indirectly
via `test_suite` rules.
### Executable targets: executables
```
expr ::= executables(expr)
```
The `executables(x)` operator returns the set of all
executable targets in set x. These targets
are of rule types that can be run with `bazel run`, such as `cc_binary`,
or any other rule that sets `executable = True` in its definition.
This doesn't include test targets, which can be added to the result with
the [`tests`](#tests) operator.
### Package definition files: buildfiles
```
expr ::= buildfiles(expr)
```
The `buildfiles(x)` operator returns the set
of files that define the packages of each target in
set x; in other words, for each package, its `BUILD` file,
plus any .bzl files it references via `load`. Note that this
also returns the `BUILD` files of the packages containing these
`load`ed files.
This operator is typically used when determining what files or
packages are required to build a specified target, often in conjunction with
the [`--output package`](#output-package) option, below). For example,
```posix-terminal theme={null}
bazel query 'buildfiles(deps(//foo))' --output package
```
returns the set of all packages on which `//foo` transitively depends.
Note: A naive attempt at the above query would omit
the `buildfiles` operator and use only `deps`,
but this yields an incorrect result: while the result contains the
majority of needed packages, those packages that contain only files
that are `load()`'ed will be missing.
Warning: Bazel pretends each `.bzl` file produced by
`buildfiles` has a corresponding target (for example, file `a/b.bzl` =>
target `//a:b.bzl`), but this isn't necessarily the case. Therefore,
`buildfiles` doesn't compose well with other query operators and its results can be
misleading when formatted in a structured way, such as
[`--output=xml`](#xml).
### Package definition files: rbuildfiles
```
expr ::= rbuildfiles(word, ...)
```
Note: Only available with [Sky Query](#sky-query).
The `rbuildfiles` operator takes a comma-separated list of path fragments and returns
the set of `BUILD` files that transitively depend on these path fragments. For instance, if
`//foo` is a package, then `rbuildfiles(foo/BUILD)` will return the
`//foo:BUILD` target. If the `foo/BUILD` file has
`load('//bar:file.bzl'...` in it, then `rbuildfiles(bar/file.bzl)` will
return the `//foo:BUILD` target, as well as the targets for any other `BUILD` files that
load `//bar:file.bzl`
The scope of the rbuildfiles operator is the universe specified by the
`--universe_scope` flag. Files that do not correspond directly to `BUILD` files and `.bzl`
files do not affect the results. For instance, source files (like `foo.cc`) are ignored,
even if they are explicitly mentioned in the `BUILD` file. Symlinks, however, are respected, so that
if `foo/BUILD` is a symlink to `bar/BUILD`, then
`rbuildfiles(bar/BUILD)` will include `//foo:BUILD` in its results.
The `rbuildfiles` operator is almost morally the inverse of the
[`buildfiles`](#buildfiles) operator. However, this moral inversion
holds more strongly in one direction: the outputs of `rbuildfiles` are just like the
inputs of `buildfiles`; the former will only contain `BUILD` file targets in packages,
and the latter may contain such targets. In the other direction, the correspondence is weaker. The
outputs of the `buildfiles` operator are targets corresponding to all packages and .`bzl`
files needed by a given input. However, the inputs of the `rbuildfiles` operator are
not those targets, but rather the path fragments that correspond to those targets.
### Package definition files: loadfiles
```
expr ::= loadfiles(expr)
```
The `loadfiles(x)` operator returns the set of
Starlark files that are needed to load the packages of each target in
set x. In other words, for each package, it returns the
.bzl files that are referenced from its `BUILD` files.
Warning: Bazel pretends each of these .bzl files has a corresponding target
(for example, file `a/b.bzl` => target `//a:b.bzl`), but this isn't
necessarily the case. Therefore, `loadfiles` doesn't compose well with other query
operators and its results can be misleading when formatted in a structured way, such as
[`--output=xml`](#xml).
## Output formats
`bazel query` generates a graph.
You specify the content, format, and ordering by which
`bazel query` presents this graph
by means of the `--output` command-line option.
When running with [Sky Query](#sky-query), only output formats that are compatible with
unordered output are allowed. Specifically, `graph`, `minrank`, and
`maxrank` output formats are forbidden.
Some of the output formats accept additional options. The name of
each output option is prefixed with the output format to which it
applies, so `--graph:factored` applies only
when `--output=graph` is being used; it has no effect if
an output format other than `graph` is used. Similarly,
`--xml:line_numbers` applies only when `--output=xml`
is being used.
### On the ordering of results
Although query expressions always follow the "[law of conservation of graph order](#graph-order)", *presenting* the results may be done
in either a dependency-ordered or unordered manner. This does **not**
influence the targets in the result set or how the query is computed. It only
affects how the results are printed to stdout. Moreover, nodes that are
equivalent in the dependency order may or may not be ordered alphabetically.
The `--order_output` flag can be used to control this behavior.
(The `--[no]order_results` flag has a subset of the functionality
of the `--order_output` flag and is deprecated.)
The default value of this flag is `auto`, which prints results in **lexicographical
order**. However, when `somepath(a,b)` is used, the results will be printed in
`deps` order instead.
When this flag is `no` and `--output` is one of
`build`, `label`, `label_kind`, `location`, `package`, `proto`, or
`xml`, the outputs will be printed in arbitrary order. **This is
generally the fastest option**. It is not supported though when
`--output` is one of `graph`, `minrank` or
`maxrank`: with these formats, Bazel always prints results
ordered by the dependency order or rank.
When this flag is `deps`, Bazel prints results in some topological order—that is,
dependents first and dependencies after. However, nodes that are unordered by the
dependency order (because there is no path from either one to the other) may be
printed in any order.
When this flag is `full`, Bazel prints nodes in a fully deterministic (total) order.
First, all nodes are sorted alphabetically. Then, each node in the list is used as the start of a
post-order depth-first search in which outgoing edges to unvisited nodes are traversed in
alphabetical order of the successor nodes. Finally, nodes are printed in the reverse of the order
in which they were visited.
Printing nodes in this order may be slower, so it should be used only when determinism is
important.
### Print the source form of targets as they would appear in BUILD
```
--output build
```
With this option, the representation of each target is as if it were
hand-written in the BUILD language. All variables and function calls
(such as glob, macros) are expanded, which is useful for seeing the effect
of Starlark macros. Additionally, each effective rule reports a
`generator_name` and/or `generator_function`) value,
giving the name of the macro that was evaluated to produce the effective rule.
Although the output uses the same syntax as `BUILD` files, it is not
guaranteed to produce a valid `BUILD` file.
### Print the label of each target
```
--output label
```
With this option, the set of names (or *labels*) of each target
in the resulting graph is printed, one label per line, in
topological order (unless `--noorder_results` is specified, see
[notes on the ordering of results](#result-order)).
(A topological ordering is one in which a graph
node appears earlier than all of its successors.) Of course there
are many possible topological orderings of a graph (*reverse
postorder* is just one); which one is chosen is not specified.
When printing the output of a `somepath` query, the order
in which the nodes are printed is the order of the path.
Caveat: in some corner cases, there may be two distinct targets with
the same label; for example, a `sh_binary` rule and its
sole (implicit) `srcs` file may both be called
`foo.sh`. If the result of a query contains both of
these targets, the output (in `label` format) will appear
to contain a duplicate. When using the `label_kind` (see
below) format, the distinction becomes clear: the two targets have
the same name, but one has kind `sh_binary rule` and the
other kind `source file`.
### Print the label and kind of each target
```
--output label_kind
```
Like `label`, this output format prints the labels of
each target in the resulting graph, in topological order, but it
additionally precedes the label by the [*kind*](#kind) of the target.
### Print targets in protocol buffer format
```
--output proto
```
Prints the query output as a
[`QueryResult`](https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/build.proto)
protocol buffer.
### Print targets in length-delimited protocol buffer format
```
--output streamed_proto
```
Prints a
[length-delimited](https://protobuf.dev/programming-guides/encoding/#size-limit)
stream of
[`Target`](https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/build.proto)
protocol buffers. This is useful to *(i)* get around
[size limitations](https://protobuf.dev/programming-guides/encoding/#size-limit)
of protocol buffers when there are too many targets to fit in a single
`QueryResult` or *(ii)* to start processing while Bazel is still outputting.
### Print targets in text proto format
```
--output textproto
```
Similar to `--output proto`, prints the
[`QueryResult`](https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/build.proto)
protocol buffer but in
[text format](https://protobuf.dev/reference/protobuf/textformat-spec/).
### Print targets in ndjson format
```
--output streamed_jsonproto
```
Similar to `--output streamed_proto`, prints a stream of
[`Target`](https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/build.proto)
protocol buffers but in [ndjson](https://github.com/ndjson/ndjson-spec) format.
### Print the label of each target, in rank order
```
--output minrank --output maxrank
```
Like `label`, the `minrank`
and `maxrank` output formats print the labels of each
target in the resulting graph, but instead of appearing in
topological order, they appear in rank order, preceded by their
rank number. These are unaffected by the result ordering
`--[no]order_results` flag (see [notes on the ordering of results](#result-order)).
There are two variants of this format: `minrank` ranks
each node by the length of the shortest path from a root node to it.
"Root" nodes (those which have no incoming edges) are of rank 0,
their successors are of rank 1, etc. (As always, edges point from a
target to its prerequisites: the targets it depends upon.)
`maxrank` ranks each node by the length of the longest
path from a root node to it. Again, "roots" have rank 0, all other
nodes have a rank which is one greater than the maximum rank of all
their predecessors.
All nodes in a cycle are considered of equal rank. (Most graphs are
acyclic, but cycles do occur
simply because `BUILD` files contain erroneous cycles.)
These output formats are useful for discovering how deep a graph is.
If used for the result of a `deps(x)`, `rdeps(x)`,
or `allpaths` query, then the rank number is equal to the
length of the shortest (with `minrank`) or longest
(with `maxrank`) path from `x` to a node in
that rank. `maxrank` can be used to determine the
longest sequence of build steps required to build a target.
Note: The ranked output of a `somepath` query is
basically meaningless because `somepath` doesn't
guarantee to return either a shortest or a longest path, and it may
include "transitive" edges from one path node to another that are
not direct edges in original graph.
For example, the graph on the left yields the outputs on the right
when `--output minrank` and `--output maxrank`
are specified, respectively.
### Print the location of each target
```
--output location
```
Like `label_kind`, this option prints out, for each
target in the result, the target's kind and label, but it is
prefixed by a string describing the location of that target, as a
filename and line number. The format resembles the output of
`grep`. Thus, tools that can parse the latter (such as Emacs
or vi) can also use the query output to step through a series of
matches, allowing the Bazel query tool to be used as a
dependency-graph-aware "grep for BUILD files".
The location information varies by target kind (see the [kind](#kind) operator). For rules, the
location of the rule's declaration within the `BUILD` file is printed.
For source files, the location of line 1 of the actual file is
printed. For a generated file, the location of the rule that
generates it is printed. (The query tool does not have sufficient
information to find the actual location of the generated file, and
in any case, it might not exist if a build has not yet been performed.)
### Print the set of packages
```
--output package
```
This option prints the name of all packages to which
some target in the result set belongs. The names are printed in
lexicographical order; duplicates are excluded. Formally, this
is a *projection* from the set of labels (package, target) onto
packages.
Packages in external repositories are formatted as
`@repo//foo/bar` while packages in the main repository are
formatted as `foo/bar`.
In conjunction with the `deps(...)` query, this output
option can be used to find the set of packages that must be checked
out in order to build a given set of targets.
### Display a graph of the result
```
--output graph
```
This option causes the query result to be printed as a directed
graph in the popular AT\&T GraphViz format. Typically the
result is saved to a file, such as `.png` or `.svg`.
(If the `dot` program is not installed on your workstation, you
can install it using the command `sudo apt-get install graphviz`.)
See the example section below for a sample invocation.
This output format is particularly useful for `allpaths`,
`deps`, or `rdeps` queries, where the result
includes a *set of paths* that cannot be easily visualized when
rendered in a linear form, such as with `--output label`.
By default, the graph is rendered in a *factored* form. That is,
topologically-equivalent nodes are merged together into a single
node with multiple labels. This makes the graph more compact
and readable, because typical result graphs contain highly
repetitive patterns. For example, a `java_library` rule
may depend on hundreds of Java source files all generated by the
same `genrule`; in the factored graph, all these files
are represented by a single node. This behavior may be disabled
with the `--nograph:factored` option.
#### `--graph:node_limit n`
The option specifies the maximum length of the label string for a
graph node in the output. Longer labels will be truncated; -1
disables truncation. Due to the factored form in which graphs are
usually printed, the node labels may be very long. GraphViz cannot
handle labels exceeding 1024 characters, which is the default value
of this option. This option has no effect unless
`--output=graph` is being used.
#### `--[no]graph:factored`
By default, graphs are displayed in factored form, as explained
[above](#output-graph).
When `--nograph:factored` is specified, graphs are
printed without factoring. This makes visualization using GraphViz
impractical, but the simpler format may ease processing by other
tools (such as grep). This option has no effect
unless `--output=graph` is being used.
### XML
```
--output xml
```
This option causes the resulting targets to be printed in an XML
form. The output starts with an XML header such as this
```
```
and then continues with an XML element for each target
in the result graph, in topological order (unless
[unordered results](#result-order) are requested),
and then finishes with a terminating
```
```
Simple entries are emitted for targets of `file` kind:
```
```
But for rules, the XML is structured and contains definitions of all
the attributes of the rule, including those whose value was not
explicitly specified in the rule's `BUILD` file.
Additionally, the result includes `rule-input` and
`rule-output` elements so that the topology of the
dependency graph can be reconstructed without having to know that,
for example, the elements of the `srcs` attribute are
forward dependencies (prerequisites) and the contents of the
`outs` attribute are backward dependencies (consumers).
`rule-input` elements for [implicit dependencies](#implicit_deps) are suppressed if
`--noimplicit_deps` is specified.
```
...
...
...
...
```
Every XML element for a target contains a `name`
attribute, whose value is the target's label, and
a `location` attribute, whose value is the target's
location as printed by the [`--output location`](#print-target-location).
#### `--[no]xml:line_numbers`
By default, the locations displayed in the XML output contain line numbers.
When `--noxml:line_numbers` is specified, line numbers are not printed.
#### `--[no]xml:default_values`
By default, XML output does not include rule attribute whose value
is the default value for that kind of attribute (for example, if it
were not specified in the `BUILD` file, or the default value was
provided explicitly). This option causes such attribute values to
be included in the XML output.
### Regular expressions
Regular expressions in the query language use the Java regex library, so you can use the
full syntax for
[`java.util.regex.Pattern`](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html).
### Querying with external repositories
If the build depends on rules from [external repositories](/external/overview)
then query results will include these dependencies. For
example, if `//foo:bar` depends on `@other-repo//baz:lib`, then
`bazel query 'deps(//foo:bar)'` will list `@other-repo//baz:lib` as a
dependency.
# Query quickstart
Source: https://bazel.build/query/quickstart
This tutorial covers how to work with Bazel to trace dependencies in your code using a premade Bazel project.
For language and `--output` flag details, see the [Bazel query reference](/query/language) and [Bazel cquery reference](/query/cquery) manuals. Get help in your IDE by typing `bazel help query` or `bazel help cquery` on the command line.
## Objective
This guide runs you through a set of basic queries you can use to learn more about your project's file dependencies. It is intended for new Bazel developers with a basic knowledge of how Bazel and `BUILD` files work.
## Prerequisites
Start by installing [Bazel](https://bazel.build/install), if you haven’t already. This tutorial uses Git for source control, so for best results, install [Git](https://github.com/git-guides/install-git) as well.
To visualize dependency graphs, the tool called Graphviz is used, which you can [download](https://graphviz.org/download/) in order to follow along.
### Get the sample project
Next, retrieve the sample app from [Bazel's Examples repository](https://github.com/bazelbuild/examples) by running the following in your command-line tool of choice:
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/examples.git
```
The sample project for this tutorial is in the `examples/query-quickstart` directory.
## Getting started
### What are Bazel queries?
Queries help you to learn about a Bazel codebase by analyzing the relationships between `BUILD` files and examining the resulting output for useful information. This guide previews some basic query functions, but for more options see the [query guide](https://bazel.build/query/guide). Queries help you learn about dependencies in large scale projects without manually navigating through `BUILD` files.
To run a query, open your command line terminal and enter:
```posix-terminal theme={null}
bazel query 'query_function'
```
### Scenario
Imagine a scenario that delves into the relationship between Cafe Bazel and its respective chef. This Cafe exclusively sells pizza and mac & cheese. Take a look below at how the project is structured:
```
bazelqueryguide
├── BUILD
├── src
│ └── main
│ └── java
│ └── com
│ └── example
│ ├── customers
│ │ ├── Jenny.java
│ │ ├── Amir.java
│ │ └── BUILD
│ ├── dishes
│ │ ├── Pizza.java
│ │ ├── MacAndCheese.java
│ │ └── BUILD
│ ├── ingredients
│ │ ├── Cheese.java
│ │ ├── Tomatoes.java
│ │ ├── Dough.java
│ │ ├── Macaroni.java
│ │ └── BUILD
│ ├── restaurant
│ │ ├── Cafe.java
│ │ ├── Chef.java
│ │ └── BUILD
│ ├── reviews
│ │ ├── Review.java
│ │ └── BUILD
│ └── Runner.java
└── MODULE.bazel
```
Throughout this tutorial, unless directed otherwise, try not to look in the `BUILD` files to find the information you need and instead solely use the query function.
A project consists of different packages that make up a Cafe. They are separated into: `restaurant`, `ingredients`, `dishes`, `customers`, and `reviews`. Rules within these packages define different components of the Cafe with various tags and dependencies.
### Running a build
This project contains a main method inside of `Runner.java` that you can execute
to print out a menu of the Cafe. Build the project using Bazel with the command
`bazel build` and use `:` to signal that the target is named `runner`. See
[target names](https://bazel.build/concepts/labels#target-names) to learn how to
reference targets.
To build this project, paste this command into a terminal:
```posix-terminal theme={null}
bazel build :runner
```
Your output should look something like this if the build is successful.
```bash theme={null}
INFO: Analyzed target //:runner (49 packages loaded, 784 targets configured).
INFO: Found 1 target...
Target //:runner up-to-date:
bazel-bin/runner.jar
bazel-bin/runner
INFO: Elapsed time: 16.593s, Critical Path: 4.32s
INFO: 23 processes: 4 internal, 10 darwin-sandbox, 9 worker.
INFO: Build completed successfully, 23 total actions
```
After it has built successfully, run the application by pasting this command:
```posix-terminal theme={null}
bazel-bin/runner
```
```bash theme={null}
--------------------- MENU -------------------------
Pizza - Cheesy Delicious Goodness
Macaroni & Cheese - Kid-approved Dinner
----------------------------------------------------
```
This leaves you with a list of the menu items given along with a short description.
## Exploring targets
The project lists ingredients and dishes in their own packages. To use a query to view the rules of a package, run the command bazel query package/…
In this case, you can use this to look through the ingredients and dishes that this Cafe has by running:
```posix-terminal theme={null}
bazel query //src/main/java/com/example/dishes/...
```
```posix-terminal theme={null}
bazel query //src/main/java/com/example/ingredients/...
```
If you query for the targets of the ingredients package, the output should look like:
```bash theme={null}
//src/main/java/com/example/ingredients:cheese
//src/main/java/com/example/ingredients:dough
//src/main/java/com/example/ingredients:macaroni
//src/main/java/com/example/ingredients:tomato
```
## Finding dependencies
What targets does your runner rely on to run?
Say you want to dive deeper into the structure of your project without prodding into the filesystem (which may be untenable for large projects). What rules does Cafe Bazel use?
If, like in this example, the target for your runner is `runner`, discover the underlying dependencies of the target by running the command:
```posix-terminal theme={null}
bazel query --noimplicit_deps "deps(target)"
```
```posix-terminal theme={null}
bazel query --noimplicit_deps "deps(:runner)"
```
```bash theme={null}
//:runner
//:src/main/java/com/example/Runner.java
//src/main/java/com/example/dishes:MacAndCheese.java
//src/main/java/com/example/dishes:Pizza.java
//src/main/java/com/example/dishes:macAndCheese
//src/main/java/com/example/dishes:pizza
//src/main/java/com/example/ingredients:Cheese.java
//src/main/java/com/example/ingredients:Dough.java
//src/main/java/com/example/ingredients:Macaroni.java
//src/main/java/com/example/ingredients:Tomato.java
//src/main/java/com/example/ingredients:cheese
//src/main/java/com/example/ingredients:dough
//src/main/java/com/example/ingredients:macaroni
//src/main/java/com/example/ingredients:tomato
//src/main/java/com/example/restaurant:Cafe.java
//src/main/java/com/example/restaurant:Chef.java
//src/main/java/com/example/restaurant:cafe
//src/main/java/com/example/restaurant:chef
```
Note: Adding the flag `--noimplicit_deps` removes configurations and potential toolchains to simplify the list. When you omit this flag, Bazel returns implicit dependencies not specified in the `BUILD` file and clutters the output.
In most cases, use the query function `deps()` to see individual output dependencies of a specific target.
## Visualizing the dependency graph (optional)
Note: This section uses Graphviz, so make sure to [download Graphviz](https://graphviz.org/download/) to follow along.
The section describes how you can visualize the dependency paths for a specific query. [Graphviz](https://graphviz.org/) helps to see the path as a directed acyclic graph image as opposed to a flattened list. You can alter the display of the Bazel query graph by using various `--output` command line options. See [Output Formats](https://bazel.build/query/language#output-formats) for options.
Start by running your desired query and add the flag `--noimplicit_deps` to remove excessive tool dependencies. Then, follow the query with the output flag and store the graph into a file called `graph.in` to create a text representation of the graph.
To search for all dependencies of the target `:runner` and format the output as a graph:
```posix-terminal theme={null}
bazel query --noimplicit_deps 'deps(:runner)' --output graph > graph.in
```
This creates a file called `graph.in`, which is a text representation of the build graph. Graphviz uses [dot](https://graphviz.org/docs/layouts/dot/) – a tool that processes text into a visualization — to create a png:
```posix-terminal theme={null}
dot -Tpng < graph.in > graph.png
```
If you open up `graph.png`, you should see something like this. The graph below has been simplified to make the essential path details clearer in this guide.
This helps when you want to see the outputs of the different query functions throughout this guide.
## Finding reverse dependencies
If instead you have a target you’d like to analyze what other targets use it, you can use a query to examine what targets depend on a certain rule. This is called a “reverse dependency”. Using `rdeps()` can be useful when editing a file in a codebase that you’re unfamiliar with, and can save you from unknowingly breaking other files which depended on it.
For instance, you want to make some edits to the ingredient `cheese`. To avoid causing an issue for Cafe Bazel, you need to check what dishes rely on `cheese`.
Caution: Since `ingredients` is its own package, you must use a different naming convention for the target `cheese` in the form of `//package:target`. Read more about referencing targets, or [Labels](https://bazel.build/concepts/labels).
To see what targets depend on a particular target/package, you can use `rdeps(universe_scope, target)`. The `rdeps()` query function takes in at least two arguments: a `universe_scope` — the relevant directory — and a `target`. Bazel searches for the target’s reverse dependencies within the `universe_scope` provided. The `rdeps()` operator accepts an optional third argument: an integer literal specifying the upper bound on the depth of the search.
Tip: To search within the whole scope of the project, set the `universe_scope` to `//...`
To look for reverse dependencies of the target `cheese` within the scope of the entire project ‘//…’ run the command:
```posix-terminal theme={null}
bazel query "rdeps(universe_scope, target)"
```
```
ex) bazel query "rdeps(//... , //src/main/java/com/example/ingredients:cheese)"
```
```bash theme={null}
//:runner
//src/main/java/com/example/dishes:macAndCheese
//src/main/java/com/example/dishes:pizza
//src/main/java/com/example/ingredients:cheese
//src/main/java/com/example/restaurant:cafe
//src/main/java/com/example/restaurant:chef
```
The query return shows that cheese is relied on by both pizza and macAndCheese. What a surprise!
## Finding targets based on tags
Two customers walk into Bazel Cafe: Amir and Jenny. There is nothing known about them except for their names. Luckily, they have their orders tagged in the 'customers' `BUILD` file. How can you access this tag?
Developers can tag Bazel targets with different identifiers, often for testing purposes. For instance, tags on tests can annotate a test's role in your debug and release process, especially for C++ and Python tests, which lack any runtime annotation ability. Using tags and size elements gives flexibility in assembling suites of tests based around a codebase’s check-in policy.
In this example, the tags are either one of `pizza` or `macAndCheese` to represent the menu items. This command queries for targets that have tags matching your identifier within a certain package.
```
bazel query 'attr(tags, "pizza", //src/main/java/com/example/customers/...)'
```
This query returns all of the targets in the 'customers' package that have a tag of "pizza".
### Test yourself
Use this query to learn what Jenny wants to order.
Mac and Cheese
## Adding a new dependency
Cafe Bazel has expanded its menu — customers can now order a Smoothie! This specific smoothie consists of the ingredients `Strawberry` and `Banana`.
First, add the ingredients that the smoothie depends on: `Strawberry.java` and `Banana.java`. Add the empty Java classes.
**`src/main/java/com/example/ingredients/Strawberry.java`**
```java theme={null}
package com.example.ingredients;
public class Strawberry {
}
```
**`src/main/java/com/example/ingredients/Banana.java`**
```java theme={null}
package com.example.ingredients;
public class Banana {
}
```
Next, add `Smoothie.java` to the appropriate directory: `dishes`.
**`src/main/java/com/example/dishes/Smoothie.java`**
```java theme={null}
package com.example.dishes;
public class Smoothie {
public static final String DISH_NAME = "Smoothie";
public static final String DESCRIPTION = "Yummy and Refreshing";
}
```
Lastly, add these files as rules in the appropriate `BUILD` files. Create a new java library for each new ingredient, including its name, public visibility, and its newly created 'src' file. You should wind up with this updated `BUILD` file:
**`src/main/java/com/example/ingredients/BUILD`**
```
java_library(
name = "cheese",
visibility = ["//visibility:public"],
srcs = ["Cheese.java"],
)
java_library(
name = "dough",
visibility = ["//visibility:public"],
srcs = ["Dough.java"],
)
java_library(
name = "macaroni",
visibility = ["//visibility:public"],
srcs = ["Macaroni.java"],
)
java_library(
name = "tomato",
visibility = ["//visibility:public"],
srcs = ["Tomato.java"],
)
java_library(
name = "strawberry",
visibility = ["//visibility:public"],
srcs = ["Strawberry.java"],
)
java_library(
name = "banana",
visibility = ["//visibility:public"],
srcs = ["Banana.java"],
)
```
In the `BUILD` file for dishes, you want to add a new rule for `Smoothie`. Doing so includes the Java file created for `Smoothie` as a 'src' file, and the new rules you made for each ingredient of the smoothie.
**`src/main/java/com/example/dishes/BUILD`**
```
java_library(
name = "macAndCheese",
visibility = ["//visibility:public"],
srcs = ["MacAndCheese.java"],
deps = [
"//src/main/java/com/example/ingredients:cheese",
"//src/main/java/com/example/ingredients:macaroni",
],
)
java_library(
name = "pizza",
visibility = ["//visibility:public"],
srcs = ["Pizza.java"],
deps = [
"//src/main/java/com/example/ingredients:cheese",
"//src/main/java/com/example/ingredients:dough",
"//src/main/java/com/example/ingredients:tomato",
],
)
java_library(
name = "smoothie",
visibility = ["//visibility:public"],
srcs = ["Smoothie.java"],
deps = [
"//src/main/java/com/example/ingredients:strawberry",
"//src/main/java/com/example/ingredients:banana",
],
)
```
Lastly, you want to include the smoothie as a dependency in the Chef’s `BUILD` file.
**`src/main/java/com/example/restaurant/BUILD`**
```
java_library(
name = "chef",
visibility = ["//visibility:public"],
srcs = [
"Chef.java",
],
deps = [
"//src/main/java/com/example/dishes:macAndCheese",
"//src/main/java/com/example/dishes:pizza",
"//src/main/java/com/example/dishes:smoothie",
],
)
java_library(
name = "cafe",
visibility = ["//visibility:public"],
srcs = [
"Cafe.java",
],
deps = [
":chef",
],
)
```
Build `cafe` again to confirm that there are no errors. If it builds successfully, congratulations! You’ve added a new dependency for the 'Cafe'. If not, look out for spelling mistakes and package naming. For more information about writing `BUILD` files see [BUILD Style Guide](https://bazel.build/build/style-guide).
Now, visualize the new dependency graph with the addition of the `Smoothie` to compare with the previous one. For clarity, name the graph input as `graph2.in` and `graph2.png`.
```posix-terminal theme={null}
bazel query --noimplicit_deps 'deps(:runner)' --output graph > graph2.in
```
```posix-terminal theme={null}
dot -Tpng < graph2.in > graph2.png
```
[](/query/images/query_graph2.png)
Looking at `graph2.png`, you can see that `Smoothie` has no shared dependencies with other dishes but is just another target that the `Chef` relies on.
## somepath() and allpaths()
What if you want to query why one package depends on another package? Displaying a dependency path between the two provides the answer.
Two functions can help you find dependency paths: `somepath()` and `allpaths()`. Given a starting target S and an end point E, find a path between S and E by using `somepath(S,E)`.
Explore the differences between these two functions by looking at the relationships between the 'Chef' and 'Cheese' targets. There are different possible paths to get from one target to the other:
* Chef → MacAndCheese → Cheese
* Chef → Pizza → Cheese
`somepath()` gives you a single path out of the two options, whereas 'allpaths()' outputs every possible path.
Using Cafe Bazel as an example, run the following:
```posix-terminal theme={null}
bazel query "somepath(//src/main/java/com/example/restaurant/..., //src/main/java/com/example/ingredients:cheese)"
```
```bash theme={null}
//src/main/java/com/example/restaurant:cafe
//src/main/java/com/example/restaurant:chef
//src/main/java/com/example/dishes:macAndCheese
//src/main/java/com/example/ingredients:cheese
```
The output follows the first path of Cafe → Chef → MacAndCheese → Cheese. If instead you use `allpaths()`, you get:
```posix-terminal theme={null}
bazel query "allpaths(//src/main/java/com/example/restaurant/..., //src/main/java/com/example/ingredients:cheese)"
```
```bash theme={null}
//src/main/java/com/example/dishes:macAndCheese
//src/main/java/com/example/dishes:pizza
//src/main/java/com/example/ingredients:cheese
//src/main/java/com/example/restaurant:cafe
//src/main/java/com/example/restaurant:chef
```
The output of `allpaths()` is a little harder to read as it is a flattened list of the dependencies. Visualizing this graph using Graphviz makes the relationship clearer to understand.
## Test yourself
One of Cafe Bazel’s customers gave the restaurant's first review! Unfortunately, the review is missing some details such as the identity of the reviewer and what dish it’s referencing. Luckily, you can access this information with Bazel. The `reviews` package contains a program that prints a review from a mystery customer. Build and run it with:
```posix-terminal theme={null}
bazel build //src/main/java/com/example/reviews:review
```
```posix-terminal theme={null}
bazel-bin/src/main/java/com/example/reviews/review
```
Going off Bazel queries only, try to find out who wrote the review, and what dish they were describing.
Check the tags and dependencies for useful information.
This review was describing the Pizza and Amir was the reviewer. If you look at what dependencies that this rule had using
bazel query --noimplicit\_deps 'deps(//src/main/java/com/example/reviews:review)'
The result of this command reveals that Amir is the reviewer!
Next, since you know the reviewer is Amir, you can use the query function to seek which tag Amir has in the `BUILD` file to see what dish is there.
The command bazel query 'attr(tags, "pizza", //src/main/java/com/example/customers/...)' output that Amir is the only customer that ordered a pizza and is the reviewer which gives us the answer.
## Wrapping up
Congratulations! You have now run several basic queries, which you can try out on own projects. To learn more about the query language syntax, refer to the [Query reference page](https://bazel.build/query/language). Want more advanced queries? The [Query guide](https://bazel.build/query/guide) showcases an in-depth list of more use cases than are covered in this guide.
# Common definitions
Source: https://bazel.build/reference/be/common-definitions
This section defines various terms and concepts that are common to
many functions or build rules.
## Contents
* [Bourne shell tokenization](#sh-tokenization)
* [Label Expansion](#label-expansion)
* [Typical attributes defined by most build rules](#typical-attributes)
* [Attributes common to all build rules](#common-attributes)
* [Attributes common to all test rules (\*\_test)](#common-attributes-tests)
* [Attributes common to all binary rules (\*\_binary)](#common-attributes-binaries)
* [Configurable attributes](#configurable-attributes)
* [Implicit output targets](#implicit-outputs)
## Bourne shell tokenization
Certain string attributes of some rules are split into multiple
words according to the tokenization rules of the Bourne shell:
unquoted spaces delimit separate words, and single- and
double-quotes characters and backslashes are used to prevent
tokenization.
Those attributes that are subject to this tokenization are
explicitly indicated as such in their definitions in this document.
Attributes subject to "Make" variable expansion and Bourne shell
tokenization are typically used for passing arbitrary options to
compilers and other tools. Examples of such attributes are
`cc_library.copts` and `java_library.javacopts`.
Together these substitutions allow a
single string variable to expand into a configuration-specific list
of option words.
## Label expansion
Some string attributes of a very few rules are subject to label
expansion: if those strings contain a valid label as a
substring, such as `//mypkg:target`, and that label is a
declared prerequisite of the current rule, it is expanded into the
pathname of the file represented by the
[target](https://bazel.build/reference/glossary#target)
`//mypkg:target`.
Example attributes include `genrule.cmd` and
`cc_binary.linkopts`. The details may vary significantly in
each case, over such issues as: whether relative labels are
expanded; how labels that expand to multiple files are
treated, etc. Consult the rule attribute documentation for
specifics.
## Typical attributes defined by most build rules
This section describes attributes that are defined by many build rules,
but not all.
| Attribute | Description |
| - | - |
| `data` | List of [labels](/concepts/labels); default is `[]` Files needed by this rule at runtime. May list file or rule targets. Generally allows any target. The `runfiles` of targets in the `data` attribute appear in the `*.runfiles` area of any executable which is output by or has a runtime dependency on this target. This may include data files or binaries used when this target's [`srcs`](#typical.srcs) are executed. Typically, this includes the targets' default outputs and their transitive runfiles, but this depends on the implementation of the rules for those targets; most rules include their default outputs in their `runfiles`. See the [data dependencies](/concepts/dependencies#data-dependencies) section for more information about how to depend on and use data files. New rules should define a `data` attribute if they process inputs which might use other inputs at runtime. Rules' implementation functions must also [populate the target's runfiles](https://bazel.build/rules/rules#runfiles) from the outputs and runfiles of any `data` attribute, as well as runfiles from any dependency attribute which provides either source code or runtime dependencies. |
| `deps` | List of [labels](/concepts/labels); default is `[]` Dependencies for this target. Generally should only list rule targets. (Though some rules permit files to be listed directly in `deps`, this should be avoided when possible.) Language-specific rules generally limit the listed targets to those with specific [providers](https://bazel.build/extending/rules#providers). The precise semantics of what it means for a target to depend on another using `deps` are specific to the kind of rule, and the rule-specific documentation goes into more detail. For rules which process source code, `deps` generally specifies code dependencies used by the code in [`srcs`](#typical.srcs). Most often, a `deps` dependency is used to allow one module to use symbols defined in another module written in the same programming language and separately compiled. Cross-language dependencies are also permitted in many cases: For example, a `java_library` target may depend on C++ code in a `cc_library` target, by listing the latter in the `deps` attribute. See the definition of [dependencies](/concepts/build-ref#deps) for more information. |
| `licenses` | List of strings; [nonconfigurable](#configurable-attributes); default is `["none"]` A list of license-type strings to be used for this particular target. This is part of a deprecated licensing API that Bazel no longer uses. Don't use this. |
| `srcs` | List of [labels](/concepts/labels); default is `[]` Files processed or included by this rule. Generally lists files directly, but may list rule targets (like `filegroup` or `genrule`) to include their default outputs. Language-specific rules often require that the listed files have particular file extensions. |
## Attributes common to all build rules
This section describes attributes that are implicitly added to all build
rules.
| Attribute | Description |
| - | - |
| `aspect_hints` |
A list of arbitrary labels which is exposed to aspects (in particular - aspects invoked by this rule's reverse dependencies), but isn't exposed to this rule's own implementation. Consult documentation for language-specific rule sets for details about what effect a particular aspect hint would have.
You could think of an aspect hint as a richer alternative to a tag: while a tag conveys only a boolean state (the tag is either present or absent in the `tags` list), an aspect hint can convey arbitrary structured information in its providers.
In practice, aspect hints are used for interoperability between different language-specific rule sets. For example, imagine you have a `mylang_binary` target which needs to depend on an `otherlang_library` target. The MyLang-specific logic needs some additional information about the OtherLang target in order to use it, but `otherlang_library` doesn't provide this information because it knows nothing about MyLang. One solution might be for the MyLang rule set to define a `mylang_hint` rule which can be used to encode that additional information; the user can add the hint to their `otherlang_library`'s `aspect_hints`, and `mylang_binary` can use an aspect to collect the additional information from a MyLang-specific provider in the `mylang_hint`.
Targets listed in `aspect_hints` should be lightweight and minimal.
Language-specific logic should consider only aspect hints having providers relevant to that language, and should ignore any other aspect hints.
|
| `compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` The list of environments this target can be built for, in addition to default-supported environments. This is part of Bazel's constraint system, which lets users declare which targets can and cannot depend on each other. For example, externally deployable binaries shouldn't depend on libraries with company-secret code. See [ConstraintSemantics](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/analysis/constraints/ConstraintSemantics.java#L46) for details. |
| `deprecation` | String; [nonconfigurable](#configurable-attributes); default is `None` An explanatory warning message associated with this target. Typically this is used to notify users that a target has become obsolete, or has become superseded by another rule, is private to a package, or is perhaps considered harmful for some reason. It is a good idea to include some reference (like a webpage, a bug number or example migration CLs) so that one can easily find out what changes are required to avoid the message. If there is a new target that can be used as a drop in replacement, it is a good idea to just migrate all users of the old target. This attribute has no effect on the way things are built, but it may affect a build tool's diagnostic output. The build tool issues a warning when a rule with a `deprecation` attribute is depended upon by a target in another package. Intra-package dependencies are exempt from this warning, so that, for example, building the tests of a deprecated rule does not encounter a warning. If a deprecated target depends on another deprecated target, no warning message is issued. Once people have stopped using it, the target can be removed. |
| `exec_compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` A list of `constraint_values` that must be present in the execution platform of this target's default exec group. This is in addition to any constraints already set by the rule type. Constraints are used to restrict the list of available execution platforms. For more details, see the description of [toolchain resolution](/docs/toolchains#toolchain-resolution). and [exec groups](/extending/exec-groups) |
| `exec_group_compatible_with` | Dictionary of strings to lists of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `{}` A dictionary of exec group names to lists of `constraint_values` that must be present in the execution platform for the given exec group. This is in addition to any constraints already set on the exec group's definition. Constraints are used to restrict the list of available execution platforms. For more details, see the description of [toolchain resolution](/docs/toolchains#toolchain-resolution). and [exec groups](/extending/exec-groups) |
| `exec_properties` | Dictionary of strings; default is `{}` A dictionary of strings that will be added to the `exec_properties` of a platform selected for this target. See `exec_properties` of the [platform](platforms-and-toolchains#platform) rule. If a key is present in both the platform and target-level properties, the value will be taken from the target. Keys can be prefixed with the name of an execution group followed by a `.` to apply them only to that particular exec group. |
| `features` | List of *feature* strings; default is `[]` A feature is string tag that can be enabled or disabled on a target. The meaning of a feature depends on the rule itself. This `features` attribute is combined with the [package](/reference/be/functions#package) level `features` attribute. For example, if the features \["a", "b"] are enabled on the package level, and a target's `features` attribute contains \["-a", "c"], the features enabled for the rule will be "b" and "c". [See example](https://github.com/bazelbuild/examples/blob/main/rules/features/BUILD). |
| `package_metadata` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is the package's `default_package_metadata` A list of labels that are associated metadata about this target. Typically, the labels are simple rules that return a provider of constant values. Rules and aspects may use these labels to perform some additional analysis on the build graph. The canonical use case is that of [rules\_license](https://github.com/bazelbuild/rules_license). For that use case, `package_metadata` and `default_package_metadata` is used to attach information about a package's licence or version to targets. An aspect applied to a top-level binary can be used to gather those and produce compliance reports. |
| `restricted_to` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` The list of environments this target can be built for, *instead* of default-supported environments. This is part of Bazel's constraint system. See [`compatible_with`](#common.compatible_with) for details. |
| `tags` |
Tags can be used on any rule. Tags on test and `test_suite` rules are useful for categorizing the tests. Tags on non-test targets are used to control sandboxed execution of `genrule`s and Starlark actions, and for parsing by humans and/or external tools.
Bazel modifies the behavior of its sandboxing code if it finds the following keywords in the `tags` attribute of any test or `genrule` target, or the keys of `execution_requirements` for any Starlark action.
`no-sandbox` keyword results in the action or test never being sandboxed; it can still be cached or run remotely - use `no-cache` or `no-remote` to prevent either or both of those.
`no-cache` keyword results in the action or test never being cached (locally or remotely). Note: for the purposes of this tag, the disk cache is considered a local cache, whereas the HTTP and gRPC caches are considered remote. Other caches, such as Skyframe or the persistent action cache, are not affected.
`no-remote-cache` keyword results in the action or test never being cached remotely (but it may be cached locally; it may also be executed remotely). Note: for the purposes of this tag, the disk cache is considered a local cache, whereas the HTTP and gRPC caches are considered remote. Other caches, such as Skyframe or the persistent action cache, are not affected. If a combination of local disk cache and remote cache are used (combined cache), it's treated as a remote cache and disabled entirely unless `--incompatible_remote_results_ignore_disk` is set in which case the local components will be used.
`no-remote-exec` keyword results in the action or test never being executed remotely (but it may be cached remotely).
`no-remote` keyword prevents the action or test from being executed remotely or cached remotely. This is equivalent to using both `no-remote-cache` and `no-remote-exec`.
`no-remote-cache-upload` keyword disables upload part of remote caching of a spawn. it does not disable remote execution.
`local` keyword precludes the action or test from being remotely cached, remotely executed, or run inside the sandbox. For genrules and tests, marking the rule with the `local = True` attribute has the same effect.
`requires-network` keyword allows access to the external network from inside the sandbox. This tag only has an effect if sandboxing is enabled.
`block-network` keyword blocks access to the external network from inside the sandbox. In this case, only communication with localhost is allowed. This tag only has an effect if sandboxing is enabled.
`requires-fakeroot` runs the test or action as uid and gid 0 (i.e., the root user). This is only supported on Linux. This tag takes precedence over the `--sandbox_fake_username` command-line option.
Tags on tests are generally used to annotate a test's role in your debug and release process. Typically, tags are most useful for C++ and Python tests, which lack any runtime annotation ability. The use of tags and size elements gives flexibility in assembling suites of tests based around codebase check-in policy.
Bazel modifies test running behavior if it finds the following keywords in the `tags` attribute of the test rule:
`exclusive` will force the test to be run in the "exclusive" mode, ensuring that no other tests are running at the same time. Such tests will be executed in serial fashion after all build activity and non-exclusive tests have been completed. Remote execution is disabled for such tests because Bazel doesn't have control over what's running on a remote machine.
`exclusive-if-local` will force the test to be run in the "exclusive" mode if it is executed locally, but will run the test in parallel if it's executed remotely.
`manual` keyword will exclude the target from expansion of target pattern wildcards (`...`, `:*`, `:all`, etc.) and `test_suite` rules which do not list the test explicitly when computing the set of top-level targets to build/run for the `build`, `test`, and `coverage` commands. It does not affect target wildcard or test suite expansion in other contexts, including the `query` command. Note that `manual` does not imply that a target should not be built/run automatically by continuous build/test systems. For example, it may be desirable to exclude a target from `bazel test ...` because it requires specific Bazel flags, but still have it included in properly-configured presubmit or continuous test runs.
`external` keyword will force test to be unconditionally executed (regardless of `--cache_test_results` value).
See Tag Conventions in the Test Encyclopedia for more conventions on tags attached to test targets. |
| `target_compatible_with` | List of [labels](/concepts/labels); default is `[]` A list of `constraint_value`s that must be present in the target platform and `config_setting`s that must match the target configuration for this target to be considered *compatible*. This is in addition to any constraints already set by the rule type. If the target platform does not satisfy all listed constraints, or the target configuration does not match all listed config\_settings, then the target is considered *incompatible*. Incompatible targets are skipped for building and testing when the target pattern is expanded (e.g. `//...`, `:all`). When explicitly specified on the command line, incompatible targets cause Bazel to print an error and cause a build or test failure. Targets that transitively depend on incompatible targets are themselves considered incompatible. They are also skipped for building and testing. An empty list (which is the default) signifies that the target is compatible with all platforms. All rules support this attribute. For some rules this attribute has no effect. For example, specifying `target_compatible_with` for a `cc_toolchain` is not useful. See the [Platforms](/docs/platforms#skipping-incompatible-targets) page for more information about incompatible target skipping. |
| `testonly` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` except for test and test suite targets If `True`, only testonly targets (such as tests) can depend on this target. Equivalently, a rule that is not `testonly` is not allowed to depend on any rule that is `testonly`. Tests (`*_test` rules) and test suites ([test\_suite](/reference/be/general#test_suite) rules) are `testonly` by default. This attribute is intended to mean that the target should not be contained in binaries that are released to production. Because testonly is enforced at build time, not run time, and propagates virally through the dependency tree, it should be applied judiciously. For example, stubs and fakes that are useful for unit tests may also be useful for integration tests involving the same binaries that will be released to production, and therefore should probably not be marked testonly. Conversely, rules that are dangerous to even link in, perhaps because they unconditionally override normal behavior, should definitely be marked testonly. |
| `toolchains` |
The set of targets whose Make variables this target is allowed to access. These targets are either instances of rules that provide `TemplateVariableInfo` or special targets for toolchain types built into Bazel. These include:
`@bazel_tools//tools/cpp:toolchain_type`
`@rules_java//toolchains:current_java_runtime`
Note that this is distinct from the concept of toolchain resolution that is used by rule implementations for platform-dependent configuration. You cannot use this attribute to determine which specific `cc_toolchain` or `java_toolchain` a target will use.
|
| `visibility` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default varies The `visibility` attribute controls whether the target can be depended on by targets in other locations. See the documentation for [visibility](/concepts/visibility). For targets declared directly in a BUILD file or in legacy macros called from a BUILD file, the default value is the package's `default_visibility` if specified, or else `["//visibility:private"]`. For targets declared in one or more symbolic macros, the default value is always just `["//visibility:private"]` (which makes it useable only within the package containing the macro's code). |
## Attributes common to all test rules (\*\_test)
This section describes attributes that are common to all test rules.
| Attribute | Description |
| - | - |
| `args` | List of strings; subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution, and [Bourne shell tokenization](#sh-tokenization); default is `[]` Command line arguments that Bazel passes to the target when it is executed with `bazel test`. These arguments are passed before any `--test_arg` values specified on the `bazel test` command line. |
| `env` | Dictionary of strings; values are subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution; default is `{}` Specifies additional environment variables to set when the test is executed by `bazel test`. This attribute only applies to native rules, like `cc_test`, `py_test`, and `sh_test`. It does not apply to Starlark-defined test rules. For your own Starlark rules, you can add an "env" attribute and use it to populate a [RunEnvironmentInfo](/rules/lib/providers/RunEnvironmentInfo) Provider. [TestEnvironment](/rules/lib/toplevel/testing#TestEnvironment) Provider. |
| `env_inherit` | List of strings; default is `[]` Specifies additional environment variables to inherit from the external environment when the test is executed by `bazel test`. This attribute only applies to native rules, like `cc_test`, `py_test`, and `sh_test`. It does not apply to Starlark-defined test rules. |
| `size` |
String `"enormous"`, `"large"`, `"medium"`, or `"small"`; nonconfigurable; default is `"medium"`
Specifies a test target's "heaviness": how much time/resources it needs to run.
Unit tests are considered "small", integration tests "medium", and end-to-end tests "large" or "enormous". Bazel uses the size to determine a default timeout, which can be overridden using the `timeout` attribute. The timeout is for all tests in the BUILD target, not for each individual test. When the test is run locally, the `size` is additionally used for scheduling purposes: Bazel tries to respect `--local_{ram,cpu}_resources` and not overwhelm the local machine by running lots of heavy tests at the same time.
Test sizes correspond to the following default timeouts and assumed peak local resource usages:
Size
RAM (in MB)
CPU (in CPU cores)
Default timeout
small
20
1
short (1 minute)
medium
100
1
moderate (5 minutes)
large
300
1
long (15 minutes)
enormous
800
1
eternal (60 minutes)
The environment variable `TEST_SIZE` will be set to the value of this attribute when spawning the test.
|
| `timeout` |
String `"short"`, `"moderate"`, `"long"`, or `"eternal"`; nonconfigurable; default is derived from the test's `size` attribute
How long the test is expected to run before returning.
While a test's size attribute controls resource estimation, a test's timeout may be set independently. If not explicitly specified, the timeout is based on the test's size. The test timeout can be overridden with the `--test_timeout` flag, e.g. for running under certain conditions which are known to be slow. Test timeout values correspond to the following time periods:
Timeout Value
Time Period
short
1 minute
moderate
5 minutes
long
15 minutes
eternal
60 minutes
For times other than the above, the test timeout can be overridden with the `--test_timeout` bazel flag, e.g. for manually running under conditions which are known to be slow. The `--test_timeout` values are in seconds. For example `--test_timeout=120` will set the test timeout to two minutes.
The environment variable `TEST_TIMEOUT` will be set to the test timeout (in seconds) when spawning the test.
|
| `flaky` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` Marks test as flaky. If set, executes the test up to three times, marking it as failed only if it fails each time. By default, this attribute is set to False and the test is executed only once. Note, that use of this attribute is generally discouraged - tests should pass reliably when their assertions are upheld. |
| `shard_count` | Non-negative integer less than or equal to 50; default is `-1` Specifies the number of parallel shards to use to run the test. If set, this value will override any heuristics used to determine the number of parallel shards with which to run the test. Note that for some test rules, this parameter may be required to enable sharding in the first place. Also see `--test_sharding_strategy`. If test sharding is enabled, the environment variable `TEST_TOTAL_SHARDS` will be set to this value when spawning the test. Sharding requires the test runner to support the test sharding protocol. If it does not, then it will most likely run every test in every shard, which is not what you want. See [Test Sharding](/reference/test-encyclopedia#test-sharding) in the Test Encyclopedia for details on sharding. |
| `local` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` Forces the test to be run locally, without sandboxing. Setting this to True is equivalent to providing "local" as a tag (`tags=["local"]`). |
## Attributes common to all binary rules (\*\_binary)
This section describes attributes that are common to all binary rules.
| Attribute | Description |
| - | - |
| `args` | List of strings; subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution, and [Bourne shell tokenization](#sh-tokenization); [nonconfigurable](#configurable-attributes); default is `[]` Command line arguments that Bazel will pass to the target when it is executed either by the `run` command or as a test. These arguments are passed before the ones that are specified on the `bazel run` or `bazel test` command line. *NOTE: The arguments are not passed when you run the target outside of Bazel (for example, by manually executing the binary in `bazel-bin/`).* |
| `env` | Dictionary of strings; values are subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution; default is `{}` Specifies additional environment variables to set when the target is executed by `bazel run`. This attribute only applies to native rules, like `cc_binary`, `py_binary`, and `sh_binary`. It does not apply to Starlark-defined executable rules. For your own Starlark rules, you can add an "env" attribute and use it to populate a [RunEnvironmentInfo](/rules/lib/providers/RunEnvironmentInfo) Provider. *NOTE: The environment variables are not set when you run the target outside of Bazel (for example, by manually executing the binary in `bazel-bin/`).* |
| `output_licenses` | List of strings; default is `[]` The licenses of the output files that this binary generates. This is part of a deprecated licensing API that Bazel no longer uses. Don't use this. |
## Configurable attributes
Most attributes are "configurable", meaning that their values may change when
the target is built in different ways. Specifically, configurable attributes
may vary based on the flags passed to the Bazel command line, or what
downstream dependency is requesting the target. This can be used, for
instance, to customize the target for multiple platforms or compilation modes.
The following example declares different sources for different target
architectures. Running `bazel build :multiplatform_lib --cpu x86`
will build the target using `x86_impl.cc`, while substituting
`--cpu arm` will instead cause it to use `arm_impl.cc`.
```
cc_library(
name = "multiplatform_lib",
srcs = select({
":x86_mode": ["x86_impl.cc"],
":arm_mode": ["arm_impl.cc"]
})
)
config_setting(
name = "x86_mode",
values = { "cpu": "x86" }
)
config_setting(
name = "arm_mode",
values = { "cpu": "arm" }
)
```
The [`select()`](/reference/be/functions#select) function
chooses among different alternative values for a configurable attribute based
on which [`config_setting`](/reference/be/general#config_setting)
or [`constraint_value`](/reference/be/platforms-and-toolchains#constraint_value)
criteria the target's configuration satisfies.
Bazel evaluates configurable attributes after processing macros and before
processing rules (technically, between the
[loading and analysis phases](https://bazel.build/rules/concepts#evaluation-model)).
Any processing before `select()` evaluation doesn't know which
branch the `select()` chooses. Macros, for example, can't change
their behavior based on the chosen branch, and `bazel query` can
only make conservative guesses about a target's configurable dependencies. See
[this FAQ](https://bazel.build/docs/configurable-attributes#faq)
for more on using `select()` with rules and macros.
Attributes marked `nonconfigurable` in their documentation cannot
use this feature. Usually an attribute is nonconfigurable because Bazel
internally needs to know its value before it can determine how to resolve a
`select()`.
See [Configurable Build Attributes](https://bazel.build/docs/configurable-attributes) for a detailed overview.
## Implicit output targets
*Implicit outputs in C++ are deprecated. Please refrain from using it
in other languages where possible. We don't have a deprecation path yet
but they will eventually be deprecated too.*
When you define a build rule in a BUILD file, you are explicitly
declaring a new, named rule target in a package. Many build rule
functions also *implicitly* entail one or more output file
targets, whose contents and meaning are rule-specific.
For example, when you explicitly declare a
`java_binary(name='foo', ...)` rule, you are also
*implicitly* declaring an output file
target `foo_deploy.jar` as a member of the same package.
(This particular target is a self-contained Java archive suitable
for deployment.)
Implicit output targets are first-class members of the global
target graph. Just like other targets, they are built on demand,
either when specified in the top-level built command, or when they
are necessary prerequisites for other build targets. They can be
referenced as dependencies in BUILD files, and can be observed in
the output of analysis tools such as `bazel query`.
For each kind of build rule, the rule's documentation contains a
special section detailing the names and contents of any implicit
outputs entailed by a declaration of that kind of rule.
An important but somewhat subtle distinction between the
two namespaces used by the build system:
[labels](/concepts/labels) identify *targets*,
which may be rules or files, and file targets may be divided into
either source (or input) file targets and derived (or output) file
targets. These are the things you can mention in BUILD files,
build from the command-line, or examine using `bazel query`;
this is the *target namespace*. Each file target corresponds
to one actual file on disk (the "file system namespace"); each rule
target may correspond to zero, one or more actual files on disk.
There may be files on disk that have no corresponding target; for
example, `.o` object files produced during C++ compilation
cannot be referenced from within BUILD files or from the command line.
In this way, the build tool may hide certain implementation details of
how it does its job. This is explained more fully in
the [BUILD Concept Reference](/concepts/build-ref).
# Functions
Source: https://bazel.build/reference/be/functions
## Contents
* [package](#package)
* [package\_group](#package_group)
* [exports\_files](#exports_files)
* [glob](#glob)
* [select](#select)
* [subpackages](#subpackages)
## package
```
package(default_deprecation, default_package_metadata, default_testonly, default_visibility, features)
```
This function declares metadata that applies to every rule in the
package. It is used at most once within a package (BUILD file).
For the counterpart that declares metadata applying to every rule in the whole
*repository*, use the `repo()` function in the
[`REPO.bazel` file](/external/overview#repo.bazel) at the root of your repo.
The `repo()` function takes exactly the same arguments as `package()`.
The package() function should be called right after all the load() statements at the top of the
file, before any rule.
### Arguments
| Attribute | Description |
| - | - |
| `default_applicable_licenses` | Alias for [`default_package_metadata`](#package.default_package_metadata). |
| `default_visibility` | List of [labels](/concepts/labels); default is `[]` The default visibility of the top-level rule targets and symbolic macros in this package — that is, the targets and symbolic macros that are not themselves declared inside a symbolic macro. This attribute is ignored if the target or macro specifies a `visibility` value. For detailed information about the syntax of this attribute, see the documentation of [visibility](/concepts/visibility). The package default visibility does not apply to [exports\_files](#exports_files), which is public by default. |
| `default_deprecation` | String; default is `""` Sets the default [`deprecation`](common-definitions#common.deprecation) message for all rules in this package. |
| `default_package_metadata` | List of [labels](/concepts/labels); default is `[]` Sets a default list of metadata targets which apply to all other targets in the package. These are typically targets related to OSS package and license declarations. See [rules\_license](https://github.com/bazelbuild/rules_license) for examples. |
| `default_testonly` | Boolean; default is `False` except as noted Sets the default [`testonly`](common-definitions#common.testonly) property for all rules in this package. In packages under `javatests` the default value is `True`. |
| `features` | List strings; default is `[]` Sets various flags that affect the semantics of this BUILD file. This feature is mainly used by the people working on the build system to tag packages that need some kind of special handling. Do not use this unless explicitly requested by someone working on the build system. |
### Examples
The declaration below declares that the rules in this package are
visible only to members of package
group `//foo:target`. Individual visibility declarations
on a rule, if present, override this specification.
```
package(default_visibility = ["//foo:target"])
```
## package\_group
```
package_group(name, packages, includes)
```
This function defines a set of [packages](/concepts/build-ref#packages)
and associates a label with the set. The label can be referenced in
`visibility` attributes.
Package groups are primarily used for visibility control. A publicly visible
target can be referenced from every package in the source tree. A privately
visible target can only be referenced within its own package (not subpackages).
In between these extremes, a target may allow access to its own package plus any
of the packages described by one or more package groups. For a more detailed
explanation of the visibility system, see the
[visibility](common-definitions#common.visibility)
attribute.
A given package is considered to be in the group if it either matches the
`packages` attribute, or is already contained in one of the other
package groups mentioned in the `includes` attribute.
Package groups are technically targets, but are not created by rules, and do
not themselves have any visibility protection.
### Arguments
| Attribute | Description |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `packages` |
List of strings; default is `[]`
A list of zero or more package specifications.
Each package specification string can have one of the following forms:
The full name of a package, without its repository, starting with a double slash. For example, `//foo/bar` specifies the package having that name and which lives in the same repository as the package group.
As above, but with a trailing `/...`. For example, ` //foo/...` specifies the set of `//foo` and all its subpackages. `//...` specifies all packages in the current repository. `//` is used to denote the root package.
The strings `public` or `private`, which respectively specify every package or no package. (This form requires the flag `--incompatible_package_group_has_public_syntax` to be set.)
In addition, the first two kinds of package specifications may also be prefixed with `-` to indicate that they are negated.
The package group contains any package that matches at least one of its positive specifications and none of its negative specifications For instance, the value `[//foo/..., -//foo/tests/...]` includes all subpackages of `//foo` that are not also subpackages of `//foo/tests`. (`//foo` itself is included while //foo/tests itself is not.)
Aside from public visibility, there is no way to directly specify packages outside the current repository.
If this attribute is missing, it is the same as setting it to an empty list, which is also the same as setting it to a list containing only `private`.
Note: Prior to Bazel 6.0, the specification `//...` had a legacy behavior of being the same as `public`. This behavior is fixed when `--incompatible_fix_package_group_reporoot_syntax` is enabled, which is the default after Bazel 6.0.
Note: Prior to Bazel 6.0, when this attribute is serialized as part of `bazel query --output=proto` (or `--output=xml`), the leading slashes are omitted. For instance, `//pkg/foo/...` will output as `\"pkg/foo/...\"`. This behavior is fixed when `--incompatible_package_group_includes_double_slash` is enabled, which is the default after Bazel 6.0.
|
| `includes` | List of [labels](/concepts/labels); default is `[]` Other package groups that are included in this one. The labels in this attribute must refer to other package groups. Packages in referenced package groups are taken to be part of this package group. This is transitive — if package group `a` includes package group `b`, and `b` includes package group `c`, then every package in `c` will also be a member of `a`. When used together with negated package specifications, note that the set of packages for each group is first computed independently and the results are then unioned together. This means that negated specifications in one group have no effect on the specifications in another group. |
### Examples
The following `package_group` declaration specifies a
package group called "tropical" that contains tropical fruits.
```
package_group(
name = "tropical",
packages = [
"//fruits/mango",
"//fruits/orange",
"//fruits/papaya/...",
],
)
```
The following declarations specify the package groups of a fictional
application:
```
package_group(
name = "fooapp",
includes = [
":controller",
":model",
":view",
],
)
package_group(
name = "model",
packages = ["//fooapp/database"],
)
package_group(
name = "view",
packages = [
"//fooapp/swingui",
"//fooapp/webui",
],
)
package_group(
name = "controller",
packages = ["//fooapp/algorithm"],
)
```
## exports\_files
```
exports_files([label, ...], visibility, licenses)
```
`exports_files()` specifies a list of files belonging to
this package that are exported to other packages.
The BUILD file for a package may only refer directly to source files belonging
to another package if they are explicitly exported with an
`exports_files()` statement. Read more about
[visibility of files](/concepts/visibility#source-file-target-visibility).
As a legacy behaviour, also files mentioned as input to a rule are exported
with the default visibility until the flag
[`--incompatible_no_implicit_file_export`](https://github.com/bazelbuild/bazel/issues/10225)
is flipped. However, this behavior should not be relied upon and actively
migrated away from.
### Arguments
The argument is a list of names of files within the current package. A
visibility declaration can also be specified; in this case, the files will be
visible to the targets specified. If no visibility is specified, the files
will be visible to every package, even if a package default visibility was
specified in the `package`
function. The [licenses](common-definitions#common.licenses)
can also be specified.
### Example
The following example exports `golden.txt`, a
text file from the `test_data` package, so that other
packages may use it, for example, in the `data` attribute
of tests.
```
# from //test_data/BUILD
exports_files(["golden.txt"])
```
## glob
```
glob(include, exclude=[], exclude_directories=1, allow_empty=True)
```
Glob is a helper function that finds all files that match certain path patterns,
and returns a new, mutable, sorted list of their paths. Glob only searches files
in its own package, and looks only for source files (not generated files nor
other targets).
A source file's Label is included in the result if the file's package-relative
path matches any of the `include` patterns and none of the
`exclude` patterns.
The `include` and `exclude` lists contain path patterns
that are relative to the current package. Every pattern may consist of one or
more path segments. As usual with Unix paths, these segments are separated by
`/`. The segments in the pattern are matched against the segments of
the path. Segments may contain the `*` wildcard: this matches
any substring in the path segment (even the empty substring), excluding the
directory separator `/`. This wildcard can be used multiple times
within one path segment. Additionally, the `**` wildcard can match
zero or more complete path segments, but it must be declared as a standalone
path segment.
Examples:
* `foo/bar.txt` matches exactly the `foo/bar.txt` file
in this package (unless `foo/` is a subpackage)
* `foo/*.txt` matches every file in the `foo/` directory
if the file ends with `.txt` (unless `foo/` is a
subpackage)
* `foo/a*.htm*` matches every file in the `foo/`
directory that starts with `a`, then has an arbitrary string (could
be empty), then has `.htm`, and ends with another arbitrary string
(unless `foo/` is a subpackage); such as `foo/axx.htm`
and `foo/a.html` or `foo/axxx.html`
* `foo/*` matches every file in the `foo/` directory,
(unless `foo/` is a subpackage); it does not match `foo`
directory itself even if `exclude_directories` is set to
0
* `foo/**` matches every file in every non-subpackage subdirectory
under package's first level subdirectory `foo/`; if
`exclude_directories` is set to 0, `foo`
directory itself also matches the pattern; in this case, `**` is
considered to match zero path segments
* `**/a.txt` matches `a.txt` files in this package's
directory plus non-subpackage subdirectories.
* `**/bar/**/*.txt` matches every `.txt` file in every
non-subpackage subdirectory of this package, if at least one directory on the
resulting path is called `bar`, such as
`xxx/bar/yyy/zzz/a.txt` or `bar/a.txt` (remember that
`**` also matches zero segments) or `bar/zzz/a.txt`
* `**` matches every file in every non-subpackage subdirectory of
this package
* `foo**/a.txt` is an invalid pattern, because `**` must
stand on its own as a segment
* `foo/` is an invalid pattern, because the second segment defined
after `/` is an empty string
If the `exclude_directories` argument is enabled (set to 1), files of
type directory will be omitted from the results (default 1).
If the `allow_empty` argument is set to `False`, the
`glob` function will error-out if the result would otherwise be the
empty list.
There are several important limitations and caveats:
1. Since `glob()` runs during BUILD file evaluation,
`glob()` matches files only in your source tree, never
generated files. If you are building a target that requires both
source and generated files, you must append an explicit list of generated
files to the glob. See the [example](#glob_example)
below with `:mylib` and `:gen_java_srcs`.
2. If a rule has the same name as a matched source file, the rule will
"shadow" the file.
To understand this, remember that `glob()` returns a list of
paths, so using `glob()` in other rules' attribute (e.g.
`srcs = glob(["*.cc"])`) has the same effect as listing the
matched paths explicitly. If for example `glob()` yields
`["Foo.java", "bar/Baz.java"]` but there's also a rule in the
package called "Foo.java" (which is allowed, though Bazel warns about it),
then the consumer of the `glob()` will use the "Foo.java" rule
(its outputs) instead of the "Foo.java" file. See
[GitHub
issue #10395](https://github.com/bazelbuild/bazel/issues/10395#issuecomment-583714657) for more details.
3. Globs may match files in subdirectories. And subdirectory names
may be wildcarded. However...
4. Labels are not allowed to cross the package boundary and glob does
not match files in subpackages.
For example, the glob expression `**/*.cc` in package
`x` does not include `x/y/z.cc` if
`x/y` exists as a package (either as
`x/y/BUILD`, or somewhere else on the package-path). This
means that the result of the glob expression actually depends on the
existence of BUILD files — that is, the same glob expression would
include `x/y/z.cc` if there was no package called
`x/y` or it was marked as deleted using the
[--deleted\_packages](/docs/user-manual#flag--deleted_packages)
flag.
5. The restriction above applies to all glob expressions,
no matter which wildcards they use.
6. A hidden file with filename starting with `.` is completely matched by
both the `**` and the `*` wildcards. If you want to match a hidden file
with a compound pattern, your pattern needs to begin with a `.`. For example,
`*` and `.*.txt` will match `.foo.txt`, but `*.txt`
will not.
Hidden directories are also matched in the same manner. Hidden directories
may include files that are not required as inputs, and can increase the
number of unnecessarily globbed files and memory consumption. To exclude
hidden directories, add them to the "exclude" list argument.
7. The "\*\*" wildcard has one corner case: the pattern
`"**"` doesn't match the package's directory path. That is to
say, `glob(["**"], exclude_directories = False)` matches all files
and directories transitively strictly under the current package's directory
(but of course not going into directories of subpackages - see the previous
note about that).
In general, you should **try to provide an appropriate extension (e.g. \*.html)
instead of using a bare '\*'** for a glob pattern. The more explicit name
is both self documenting and ensures that you don't accidentally match backup
files, or emacs/vi/... auto-save files.
When writing build rules you can enumerate the elements of the glob. This
enables generating individual rules for every input, for example. See the
[expanded glob example](#expanded_glob_example) section below.
### Glob Examples
Create a Java library built from all java files in this directory,
and all files generated by the `:gen_java_srcs` rule.
```
java_library(
name = "mylib",
srcs = glob(["*.java"]) + [":gen_java_srcs"],
deps = "...",
)
genrule(
name = "gen_java_srcs",
outs = [
"Foo.java",
"Bar.java",
],
...
)
```
Include all txt files in directory testdata except experimental.txt.
Note that files in subdirectories of testdata will not be included. If
you want those files to be included, use a recursive glob (\*\*).
```
sh_test(
name = "mytest",
srcs = ["mytest.sh"],
data = glob(
["testdata/*.txt"],
exclude = ["testdata/experimental.txt"],
),
)
```
### Recursive Glob Examples
Make the test depend on all txt files in the testdata directory and any
of its subdirectories (and their subdirectories, and so on).
Subdirectories containing a BUILD file are ignored. (See limitations
and caveats above.)
```
sh_test(
name = "mytest",
srcs = ["mytest.sh"],
data = glob(["testdata/**/*.txt"]),
)
```
Create a library built from all java files in this directory and all
subdirectories except those whose path includes a directory named testing.
**This pattern should be avoided if possible, as it can reduce build
incrementality and therefore increase build times.**
```
java_library(
name = "mylib",
srcs = glob(
["**/*.java"],
exclude = ["**/testing/**"],
),
)
```
### Expanded Glob Examples
Create an individual genrule for \*\_test.cc in the current directory
that counts the number of lines in the file.
```
# Conveniently, the build language supports list comprehensions.
[genrule(
name = "count_lines_" + f[:-3], # strip ".cc"
srcs = [f],
outs = ["%s-linecount.txt" % f[:-3]],
cmd = "wc -l $< >$@",
) for f in glob(["*_test.cc"])]
```
If the BUILD file above is in package //foo and the package contains three
matching files, a\_test.cc, b\_test.cc and c\_test.cc then running
`bazel query '//foo:all'` will list all rules that were generated:
```
$ bazel query '//foo:all' | sort
//foo:count_lines_a_test
//foo:count_lines_b_test
//foo:count_lines_c_test
```
## select
```
select(
{conditionA: valuesA, conditionB: valuesB, ...},
no_match_error = "custom message"
)
```
`select()` is the helper function that makes a rule attribute
[configurable](common-definitions#configurable-attributes).
It can replace the right-hand side of
*almost*
any attribute assignment so its value depends on command-line Bazel flags.
You can use this, for example, to define platform-specific dependencies or to
embed different resources depending on whether a rule is built in "developer"
vs. "release" mode.
Basic use is as follows:
```
sh_binary(
name = "mytarget",
srcs = select({
":conditionA": ["mytarget_a.sh"],
":conditionB": ["mytarget_b.sh"],
"//conditions:default": ["mytarget_default.sh"]
})
)
```
This makes the `srcs` attribute of
a `sh_binary` configurable by replacing its normal label
list assignment with a `select` call that maps
configuration conditions to matching values. Each condition is a label
reference to
a `config_setting` or
`constraint_value`,
which "matches" if the target's configuration matches an expected set of
values. The value of `mytarget#srcs` then becomes whichever
label list matches the current invocation.
Notes:
* Exactly one condition is selected on any invocation.
* If multiple conditions match and one is a specialization of the others,
the specialization takes precedence. Condition B is considered a
specialization of condition A if B has all the same flags and constraint
values as A plus some additional flags or constraint values. This also
means that specialization resolution is not designed to create an ordering as
demonstrated in Example 2 below.
* If multiple conditions match and one is not a specialization of all the
others, Bazel fails with an error, unless all conditions resolve to the same value.
* The special pseudo-label `//conditions:default` is
considered to match if no other condition matches. If this condition
is left out, some other rule must match to avoid an error.
* `select` can be embedded *inside* a larger
attribute assignment. So `srcs = ["common.sh"] + select({ ":conditionA": ["myrule_a.sh"], ...})` and `srcs = select({ ":conditionA": ["a.sh"]}) + select({ ":conditionB": ["b.sh"]})` are valid expressions.
* `select` works with most, but not all, attributes. Incompatible
attributes are marked `nonconfigurable` in their documentation.
## subpackages
```
subpackages(include, exclude=[], allow_empty=True)
```
`subpackages()` is a helper function, similar to `glob()`
that lists subpackages instead of files and directories. It uses the same
path patterns as `glob()` and can match any subpackage that is a
direct descendant of the currently loading BUILD file. See [glob](#glob) for a detailed explanation and examples of include and
exclude patterns.
The resulting list of subpackages returned is in sorted order and contains
paths relative to the current loading package that match the given patterns in
`include` and not those in `exclude`.
### Example
The following example lists all the direct subpackages for the package `foo/BUILD`
```
# The following BUILD files exist:
# foo/BUILD
# foo/bar/baz/BUILD
# foo/bar/but/bad/BUILD
# foo/sub/BUILD
# foo/sub/deeper/BUILD
#
# In foo/BUILD a call to
subs1 = subpackages(include = ["**"])
# results in subs1 == ["sub", "bar/baz", "bar/but/bad"]
#
# 'sub/deeper' is not included because it is a subpackage of 'foo/sub' not of
# 'foo'
subs2 = subpackages(include = ["bar/*"])
# results in subs2 = ["bar/baz"]
#
# Since 'bar' is not a subpackage itself, this looks for any subpackages under
# all first level subdirectories of 'bar'.
subs3 = subpackages(include = ["bar/**"])
# results in subs3 = ["bar/baz", "bar/but/bad"]
#
# Since bar is not a subpackage itself, this looks for any subpackages which are
# (1) under all subdirectories of 'bar' which can be at any level, (2) not a
# subpackage of another subpackages.
subs4 = subpackages(include = ["sub"])
subs5 = subpackages(include = ["sub/*"])
subs6 = subpackages(include = ["sub/**"])
# results in subs4 and subs6 being ["sub"]
# results in subs5 = [].
#
# In subs4, expression "sub" checks whether 'foo/sub' is a package (i.e. is a
# subpackage of 'foo').
# In subs5, "sub/*" looks for subpackages under directory 'foo/sub'. Since
# 'foo/sub' is already a subpackage itself, the subdirectories will not be
# traversed anymore.
# In subs6, 'foo/sub' is a subpackage itself and matches pattern "sub/**", so it
# is returned. But the subdirectories of 'foo/sub' will not be traversed
# anymore.
```
In general it is preferred that instead of calling this function directly
that users use the 'subpackages' module of
[skylib](https://github.com/bazelbuild/bazel-skylib).
# Make Variables
Source: https://bazel.build/reference/be/make-variables
* [Use](#use)
* [Predefined variables](#predefined_variables)
* [Predefined genrule variables](#predefined_genrule_variables)
* [Predefined source/output path variables](#predefined_label_variables)
* [Custom variables](#custom_variables)
"Make" variables are a special class of expandable string variables available
to attributes marked as *"Subject to 'Make variable' substitution"*.
These can be used, for example, to inject specific toolchain paths into
user-constructed build actions.
Bazel provides both *predefined* variables, which are available to all
targets, and *custom* variables, which are defined in dependency targets
and only available to targets that depend on them.
The reason for the term "Make" is historical: the syntax and semantics of
these variables were originally intended to match [GNU
Make](https://www.gnu.org/software/make/manual/html_node/Using-Variables.html).
## Use
Attributes marked as *"Subject to 'Make variable' substitution"* can
reference the "Make" variable `FOO` as follows:
`my_attr = "prefix $(FOO) suffix"`
In other words, any substring matching `$(FOO)` gets expanded
to `FOO`'s value. If that value is `"bar"`, the final
string becomes:
`my_attr = "prefix bar suffix"`
If `FOO` doesn't correspond to a variable known to the consuming
target, Bazel fails with an error.
"Make" variables whose names are non-letter symbols, such as
`@`, can also be referenced using only a dollar sign, without
the parentheses. For example:
`my_attr = "prefix $@ suffix"`
To write `$` as a string literal (i.e. to prevent variable
expansion), write `$$`.
## Predefined variables
Predefined "Make" variables can be referenced by any attribute marked as
*"Subject to 'Make variable' substitution"* on any target.
To see the list of these variables and their values for a given set of build
options, run
`bazel info --show_make_env [build options]`
and look at the top output lines with capital letters.
[See an example of predefined variables](https://github.com/bazelbuild/examples/tree/main/make-variables#predefined-variables).
**Toolchain option variables**
* `COMPILATION_MODE`:
`fastbuild`, `dbg`, or `opt`. ([more
details](https://bazel.build/docs/user-manual#flag--compilation_mode))
**Path variables**
* `BINDIR`: The base of the generated binary tree for the target
architecture.
Note that a different tree may be used for programs that run during the
build on the host architecture, to support cross-compiling.
If you want to run a tool from within a `genrule`, the
recommended way to get its path is `$(execpath toolname)`,
where *toolname* must be listed in the `genrule`'s
`tools` attribute.
* `GENDIR`:
The base of the generated code tree for the target architecture.
**Machine architecture variables**
* `TARGET_CPU`:
The target architecture's CPU, e.g. `k8`.
## Predefined genrule variables
The following are specially available to `genrule`'s
`cmd` attribute and are
generally important for making that attribute work.
[See an example of predefined genrule variables](https://github.com/bazelbuild/examples/tree/main/make-variables#predefined-genrule-variables).
* `OUTS`: The `genrule`'s `outs` list. If you have
only one output file, you can also use `$@`.
* `SRCS`: The `genrule`'s `srcs` list (or more
precisely: the path names of the files corresponding to labels in the
`srcs` list).
If you have only one source file, you can also use `$<`.
* `<`: `SRCS`, if it is a single file. Else triggers
a build error.
* `@`: `OUTS`, if it is a single file. Else triggers a
build error.
* `RULEDIR`: The output directory of the target, that is, the
directory corresponding to the name of the package containing the target
under the `genfiles` or `bin` tree. For
`//my/pkg:my_genrule` this always ends in `my/pkg`,
even if `//my/pkg:my_genrule`'s outputs are in subdirectories.
* `@D`: The output directory. If
[outs](/reference/be/general#genrule.outs) has one entry,
this expands to the directory containing that file. If it has multiple
entries, this expands to the package's root directory in the
`genfiles` tree, *even if all output files are in the same
subdirectory*!
**Note:** Use `RULEDIR` over `@D` because
`RULEDIR` has simpler semantics and behaves the same way
regardless of the number of output files.
If the genrule needs to generate temporary intermediate files (perhaps as
a result of using some other tool like a compiler), it should attempt to
write them to `@D` (although `/tmp` will also
be writable) and remove them before finishing.
Especially avoid writing to directories containing inputs. They may be on
read-only filesystems. Even if not, doing so would trash the source tree.
**Note:** If the filenames corresponding to the input labels or the output
filenames contain spaces, `'`, or other special characters (or your
genrule is part of a Starlark macro which downstream users may invoke on such
files), then `$(SRCS)` and `$(OUTS)` are not suitable
for interpolation into a command line, as they do not have the semantics that
`"${@}"` would in Bash.
One workaround is to convert to a Bash array, with
```
mapfile SRCS <<< "$$(sed -e 's/ /\\n/g' <<'genrule_srcs_expansion'
$(SRC)
genrule_srcs_expansion
)
```
and then use `"$$\{SRCS[@]}"` in subsequent command lines in place
of `$(SRCS)`. A more robust option is to write a Starlark rule
instead.
## Predefined source/output path variables
The predefined variables `execpath`, `execpaths`,
`rootpath`, `rootpaths`, `location`, and
`locations` take label parameters (e.g. `$(execpath //foo:bar)`) and substitute the file paths denoted by that label.
For source files, this is the path relative to your workspace root.
For files that are outputs of rules, this is the file's *output path*
(see the explanation of *output files* below).
[See an example of predefined path variables](https://github.com/bazelbuild/examples/tree/main/make-variables#predefined-path-variables).
* `execpath`: Denotes the path beneath the
[execroot](/docs/output_directories)
where Bazel runs build actions.
In the above example, Bazel runs all build actions in the directory linked
by the `bazel-myproject` symlink in your workspace root. The
source file `empty.source` is linked at the path
`bazel-myproject/testapp/empty.source`. So its exec path (which
is the subpath below the root) is `testapp/empty.source`. This
is the path build actions can use to find the file.
Output files are staged similarly, but are also prefixed with the subpath
`bazel-out/cpu-compilation_mode/bin` (or for the outputs of
tools: `bazel-out/cpu-opt-exec-hash/bin`). In the above example,
`//testapp:app` is a tool because it appears in
`show_app_output`'s `tools` attribute.
So its output file `app` is written to
`bazel-myproject/bazel-out/cpu-opt-exec-hash/bin/testapp/app`.
The exec path is thus `bazel-out/cpu-opt-exec-hash/bin/testapp/app`. This extra prefix
makes it possible to build the same target for, say, two different CPUs in
the same build without the results clobbering each other.
The label passed to this variable must represent exactly one file. For
labels representing source files, this is automatically true. For labels
representing rules, the rule must generate exactly one output. If this is
false or the label is malformed, the build fails with an error.
* `rootpath`: Denotes the path that a built binary can use to
find a dependency at runtime relative to the subdirectory of its runfiles
directory corresponding to the main repository.
**Note:** This only works if [`--enable_runfiles`](/reference/command-line-reference#flag--enable_runfiles) is enabled, which is not the case on
Windows by default. Use `rlocationpath` instead for
cross-platform support.
This is similar to `execpath` but strips the configuration
prefixes described above. In the example from above this means both
`empty.source` and `app` use pure workspace-relative
paths: `testapp/empty.source` and `testapp/app`.
The `rootpath` of a file in an external repository
`repo` will start with `../repo/`, followed by the
repository-relative path.
This has the same "one output only" requirements as `execpath`.
* `rlocationpath`: The path a built binary can pass to the `Rlocation` function of a runfiles library to find a dependency at
runtime, either in the runfiles directory (if available) or using the
runfiles manifest.
This is similar to `rootpath` in that it does not contain
configuration prefixes, but differs in that it always starts with the
name of the repository. In the example from above this means that `empty.source` and `app` result in the following
paths: `myproject/testapp/empty.source` and `myproject/testapp/app`.
The `rlocationpath` of a file in an external repository
`repo` will start with `repo/`, followed by the
repository-relative path.
Passing this path to a binary and resolving it to a file system path using
the runfiles libraries is the preferred approach to find dependencies at
runtime. Compared to `rootpath`, it has the advantage that it
works on all platforms and even if the runfiles directory is not
available.
This has the same "one output only" requirements as `execpath`.
* `location`: A synonym for either `execpath` or
`rootpath`, depending on the attribute being expanded. This is
legacy pre-Starlark behavior and not recommended unless you really know what
it does for a particular rule. See [#2475](https://github.com/bazelbuild/bazel/issues/2475#issuecomment-339318016)
for details.
`execpaths`, `rootpaths`, `rlocationpaths`,
and `locations` are the plural variations of `execpath`,
`rootpath`, `rlocationpath`, and`location`,
respectively. They support labels producing multiple outputs, in which case
each output is listed separated by a space. Zero-output rules and malformed
labels produce build errors.
All referenced labels must appear in the consuming target's `srcs`,
output files, or `deps`. Otherwise the build fails. C++ targets can
also reference labels in `data`.
Labels don't have to be in canonical form: `foo`, `:foo`
and `//somepkg:foo` are all fine.
## Custom variables
Custom "Make" variables can be referenced by any attribute marked as
*"Subject to 'Make variable' substitution"*, but only on targets that
depend on other targets that *define* these variables.
As best practice all variables should be custom unless there's a really good
reason to bake them into core Bazel. This saves Bazel from having to load
potentially expensive dependencies to supply variables consuming tarets may
not care about.
**C++ toolchain variables**
The following are defined in C++ toolchain rules and available to any rule
that sets `toolchains = ["@bazel_tools//tools/cpp:toolchain_type"]`
Some rules, like `java_binary`, implicitly
include the C++ toolchain in their rule definition. They inherit these variables
automatically.
The built-in C++ rules are much more sophisticated than "run the compiler on
it". In order to support compilation modes as diverse as \*SAN, ThinLTO,
with/without modules, and carefully optimized binaries at the same time as
fast running tests on multiple platforms, the built-in rules go to great
lengths to ensure the correct inputs, outputs, and command-line flags are set
on each of potentially multiple internally generated actions.
These variables are a fallback mechanism to be used by language experts in
rare cases. If you are tempted to use them, please [contact the Bazel devs](https://bazel.build/help) first.
* `ABI`: The C++ ABI version.
* `AR`: The "ar" command from crosstool.
* `C_COMPILER`:
The C/C++ compiler identifier, e.g. `llvm`.
* `CC`: The C and C++ compiler command.
We strongly recommended always using `CC_FLAGS` in
combination with `CC`. Fail to do so at your own risk.
* `CC_FLAGS`: A minimal set of flags for the C/C++
compiler to be usable by genrules. In particular, this contains flags to
select the correct architecture if `CC` supports multiple
architectures.
* `DUMPBIN`: Microsoft COFF Binary File Dumper (dumpbin.exe) from
from Microsoft Visual Studio.
* `NM`: The "nm" command from crosstool.
* `OBJCOPY`: The objcopy command from the same suite as the C/C++
compiler.
* `STRIP`: The strip command from the same suite as the C/C++
compiler.
**Java toolchain variables**
The following are defined in Java toolchain rules and available to any rule
that sets `toolchains = ["@rules_java//toolchains:current_java_runtime"]` (or
`"@rules_java//toolchains:current_host_java_runtime"`
for the host toolchain equivalent).
Most of the tools in the JDK should not be used directly. The built-in Java
rules use much more sophisticated approaches to Java compilation and packaging
than upstream tools can express, such as interface Jars, header interface
Jars, and highly optimized Jar packaging and merging implementations.
These variables are a fallback mechanism to be used by language experts in
rare cases. If you are tempted to use them, please [contact the Bazel devs](https://bazel.build/help) first.
* `JAVA`: The "java" command (a Java virtual
machine). Avoid this, and use a `java_binary` rule
instead where possible. May be a relative path. If you must change
directories before invoking `java`, you need to capture the
working directory before changing it.
* `JAVABASE`: The base directory containing the
Java utilities. May be a relative path. It will have a "bin"
subdirectory.
**Starlark-defined variables**
Rule and [toolchain](/docs/toolchains) writers can define
completely custom variables by returning a
[TemplateVariableInfo](/rules/lib/TemplateVariableInfo)
provider. Any rules depending on these through the
`toolchains` attribute can then read their values:
[See an example of Starlark-defined variables](https://github.com/bazelbuild/examples/tree/main/make-variables#custom-starlark-defined-variables).
# Bazel BUILD Encyclopedia of Functions
Source: https://bazel.build/reference/be/overview
## Concepts and terminology
* [Common definitions](/reference/be/common-definitions)
* [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization)
* [Label expansion](/reference/be/common-definitions#label-expansion)
* [Typical attributes for most rules](/reference/be/common-definitions#typical-attributes)
* [Common attributes for all rules](/reference/be/common-definitions#common-attributes)
* [Common attributes for tests](/reference/be/common-definitions#common-attributes-tests)
* [Common attributes for binaries](/reference/be/common-definitions#common-attributes-binaries)
* [Configurable attributes](/reference/be/common-definitions#configurable-attributes)
* [Implicit output targets](/reference/be/common-definitions#implicit-outputs)
* ["Make" variables](/reference/be/make-variables)
* [Use](/reference/be/make-variables#use)
## Functions
* [package](/reference/be/functions#package)
* [package\_group](/reference/be/functions#package_group)
* [exports\_files](/reference/be/functions#exports_files)
* [glob](/reference/be/functions#glob)
* [select](/reference/be/functions#select)
## Rules
Native rules ship with the Bazel binary and do not require a `load` statement.
Native rules are available globally in BUILD files. In .bzl files, you can find them in
the `native` module.
For non-native Starlark rules that ship separately from Bazel, see the list of
[recommended rules](/rules/rules#recommended-rules).
### Language-specific native rules
| Language | Flags | Binary rules | Library rules | Test rules | Other rules |
| - | - | - | - | - | - |
| C / C++ | | [cc\_binary](c-cpp#cc_binary) | [cc\_import](c-cpp#cc_import) [cc\_library](c-cpp#cc_library) [cc\_shared\_library](c-cpp#cc_shared_library) [cc\_static\_library](c-cpp#cc_static_library) | [cc\_test](c-cpp#cc_test) | [cc\_toolchain](c-cpp#cc_toolchain) [fdo\_prefetch\_hints](c-cpp#fdo_prefetch_hints) [fdo\_profile](c-cpp#fdo_profile) [memprof\_profile](c-cpp#memprof_profile) [propeller\_optimize](c-cpp#propeller_optimize) |
| Java | | [java\_binary](java#java_binary) | [java\_import](java#java_import) [java\_library](java#java_library) | [java\_test](java#java_test) | [java\_package\_configuration](java#java_package_configuration) [java\_plugin](java#java_plugin) [java\_runtime](java#java_runtime) [java\_toolchain](java#java_toolchain) |
| Objective-C | | | [objc\_import](objective-c#objc_import) [objc\_library](objective-c#objc_library) | | |
| Protocol Buffer | | | [cc\_proto\_library](protocol-buffer#cc_proto_library) [java\_lite\_proto\_library](protocol-buffer#java_lite_proto_library) [java\_proto\_library](protocol-buffer#java_proto_library) [proto\_library](protocol-buffer#proto_library) [py\_proto\_library](protocol-buffer#py_proto_library) | | [proto\_lang\_toolchain](protocol-buffer#proto_lang_toolchain) [proto\_toolchain](protocol-buffer#proto_toolchain) |
| Python | | [py\_binary](python#py_binary) | [py\_library](python#py_library) | [py\_test](python#py_test) | [py\_runtime](python#py_runtime) |
| Shell | | [sh\_binary](shell#sh_binary) | [sh\_library](shell#sh_library) | [sh\_test](shell#sh_test) | |
### Language-agnostic native rules
| Family | Rules |
| - | - |
| Extra Actions |
|
# Platforms and Toolchains Rules
Source: https://bazel.build/reference/be/platforms-and-toolchains
This set of rules exists to allow you to model specific hardware platforms you are
building for and specify the specific tools you may need to compile code for those platforms.
The user should be familiar with the concepts explained [here](/extending/platforms).
## Rules
* [constraint\_setting](#constraint_setting)
* [constraint\_value](#constraint_value)
* [platform](#platform)
* [toolchain](#toolchain)
* [toolchain\_type](#toolchain_type)
## constraint\_setting
[View rule source](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/ConstraintSettingRule.java)
```
constraint_setting(name, aspect_hints, default_constraint_value, deprecation, features, licenses, refines_constraint_value, tags, testonly, visibility)
```
This rule is used to introduce a new constraint type for which a platform may specify a value.
For instance, you might define a `constraint_setting` named "glibc\_version" to represent
the capability for platforms to have different versions of the glibc library installed.
For more details, see the
[Platforms](https://bazel.build/docs/platforms) page.
Each `constraint_setting` has an extensible set of associated
`constraint_value`s. Usually these are defined in the same package, but sometimes a
different package will introduce new values for an existing setting. For instance, the predefined
setting `@platforms//cpu:cpu` can be extended with a custom value in order to
define a platform targeting an obscure cpu architecture.
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `default_constraint_value` | [Name](/concepts/labels#target-names); [nonconfigurable](common-definitions#configurable-attributes); default is `None` The label of the default value for this setting, to be used if no value is given. If this attribute is present, the `constraint_value` it points to must be defined in the same package as this `constraint_setting`. If a constraint setting has a default value, then whenever a platform does not include any constraint value for that setting, it is the same as if the platform had specified the default value. Otherwise, if there is no default value, the constraint setting is considered to be unspecified by that platform. In that case, the platform would not match against any constraint list (such as for a `config_setting`) that requires a particular value for that setting. |
| `refines_constraint_value` | [Label](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `None` The label of a `constraint_value` that this setting refines. If set, any `platform` that specifies a non-default `constraint_value` for this setting must also specify the refined `constraint_value` in its `constraint_values` attribute. Platforms that resolve to the default `constraint_value` for this setting (either implicitly via `default_constraint_value` or explicitly) are exempt from this requirement. When both the refined `constraint_value` and a `constraint_value` for this setting appear as conditions in the same `select` and both are satisfied, the condition that includes the refining `constraint_value` is considered more specific and is chosen unambiguously. |
## constraint\_value
[View rule source](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/ConstraintValueRule.java)
```
constraint_value(name, aspect_hints, constraint_setting, deprecation, features, licenses, tags, testonly, visibility)
```
This rule introduces a new value for a given constraint type.
For more details, see the
[Platforms](https://bazel.build/docs/platforms) page.
#### Example
The following creates a new possible value for the predefined `constraint_value`
representing cpu architecture.
```
constraint_value(
name = "mips",
constraint_setting = "@platforms//cpu:cpu",
)
```
Platforms can then declare that they have the `mips` architecture as an alternative to
`x86_64`, `arm`, and so on.
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `constraint_setting` | [Label](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); required The `constraint_setting` for which this `constraint_value` is a possible choice. |
## platform
[View rule source](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/PlatformRule.java)
```
platform(name, aspect_hints, constraint_values, deprecation, exec_properties, features, flags, licenses, missing_toolchain_error, parents, required_settings, tags, testonly, visibility)
```
This rule defines a new platform -- a named collection of constraint choices
(such as cpu architecture or compiler version) describing an environment in
which part of the build may run.
For more details, see the [Platforms](/extending/platforms) page.
#### Example
This defines a platform that describes any environment running Linux on ARM.
```
platform(
name = "linux_arm",
constraint_values = [
"@platforms//os:linux",
"@platforms//cpu:arm",
],
)
```
### Platform Flags
Platforms may use the `flags` attribute to specify a list of flags that will be added
to the configuration whenever the platform is used as the target platform (i.e., as the value of
the `--platforms` flag).
Flags set from the platform effectively have the highest precedence and overwrite any previous
value for that flag, from the command line, rc file, or transition.
#### Example
```
platform(
name = "foo",
flags = [
"--dynamic_mode=fully",
"--//bool_flag",
"--no//package:other_bool_flag",
],
)
```
This defines a platform named `foo`. When this is the target platform (either because
the user specified `--platforms//:foo`, because a transition set the
`//command_line_option:platforms` flag to `["//:foo"]`, or because
`//:foo` was used as an execution platform), then the given flags will be set in the
configuration.
#### Platforms and Repeatable Flags
Some flags will accumulate values when they are repeated, such as `--features`,
`--copt`, any Starlark flag created as `config.string(repeatable = True)`.
These flags are not compatible with setting the flags from the platform: instead, all previous
values will be removed and overwritten with the values from the platform.
As an example, given the following platform, the invocation `build --platforms=//:repeat_demo --features feature_a --features feature_b` will end up with the value of the
`--feature` flag being `["feature_c", "feature_d"]`, removing the features
set on the command line.
```
platform(
name = "repeat_demo",
flags = [
"--features=feature_c",
"--features=feature_d",
],
)
```
For this reason, it is discouraged to use repeatable flags in the `flags` attribute.
### Platform Inheritance
Platforms may use the `parents` attribute to specify another platform that they will
inherit constraint values from. Although the `parents` attribute takes a list, no
more than a single value is currently supported, and specifying multiple parents is an error.
When checking for the value of a constraint setting in a platform, first the values directly set
(via the `constraint_values` attribute) are checked, and then the constraint values on
the parent. This continues recursively up the chain of parent platforms. In this manner, any
values set directly on a platform will override the values set on the parent.
Platforms inherit the `exec_properties` attribute from the parent platform.
The dictionary entries in `exec_properties` of the parent and child platforms
will be combined.
If the same key appears in both the parent's and the child's `exec_properties`,
the child's value will be used. If the child platform specifies an empty string as a value, the
corresponding property will be unset.
#### Example: Constraint Values
```
platform(
name = "parent",
constraint_values = [
"@platforms//os:linux",
"@platforms//cpu:arm",
],
)
platform(
name = "child_a",
parents = [":parent"],
constraint_values = [
"@platforms//cpu:x86_64",
],
)
platform(
name = "child_b",
parents = [":parent"],
)
```
In this example, the child platforms have the following properties:
* `child_a` has the constraint values `@platforms//os:linux` (inherited
from the parent) and `@platforms//cpu:x86_64` (set directly on the platform).
* `child_b` inherits all constraint values from the parent, and doesn't set any of
its own.
#### Example: Execution properties
```
platform(
name = "parent",
exec_properties = {
"k1": "v1",
"k2": "v2",
},
)
platform(
name = "child_a",
parents = [":parent"],
)
platform(
name = "child_b",
parents = [":parent"],
exec_properties = {
"k1": "child"
}
)
platform(
name = "child_c",
parents = [":parent"],
exec_properties = {
"k1": ""
}
)
platform(
name = "child_d",
parents = [":parent"],
exec_properties = {
"k3": "v3"
}
)
```
In this example, the child platforms have the following properties:
* `child_a` inherits the "exec\_properties" of the parent and does not set its own.
* `child_b` inherits the parent's `exec_properties` and overrides the
value of `k1`. Its `exec_properties` will be:
`{ "k1": "child", "k2": "v2" }`.
* `child_c` inherits the parent's `exec_properties` and unsets
`k1`. Its `exec_properties` will be:
`{ "k2": "v2" }`.
* `child_d` inherits the parent's `exec_properties` and adds a new
property. Its `exec_properties` will be:
`{ "k1": "v1", "k2": "v2", "k3": "v3" }`.
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `constraint_values` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` The combination of constraint choices that this platform comprises. In order for a platform to apply to a given environment, the environment must have at least the values in this list. Each `constraint_value` in this list must be for a different `constraint_setting`. For example, you cannot define a platform that requires the cpu architecture to be both `@platforms//cpu:x86_64` and `@platforms//cpu:arm`. |
| `exec_properties` | Dictionary: String -> String; [nonconfigurable](common-definitions#configurable-attributes); default is `{}` A map of strings that affect the way actions are executed remotely. Bazel makes no attempt to interpret this, it is treated as opaque data that's forwarded via the Platform field of the [remote execution protocol](https://github.com/bazelbuild/remote-apis). This includes any data from the parent platform's `exec_properties` attributes. If the child and parent platform define the same keys, the child's values are kept. Any keys associated with a value that is an empty string are removed from the dictionary. |
| `flags` | List of strings; [nonconfigurable](common-definitions#configurable-attributes); default is `[]` A list of flags that will be enabled when this platform is used as the target platform in a configuration. Only flags that are part of the configuration can be set, such as those that can be used in transitions, or the `--define` flag. |
| `missing_toolchain_error` | String; [nonconfigurable](common-definitions#configurable-attributes); default is `"For more information on platforms or toolchains see https://bazel.build/concepts/platforms-intro."` A custom error message that is displayed when a mandatory toolchain requirement cannot be satisfied for this target platform. Intended to point to relevant documentation users can read to understand why their toolchains are misconfigured. Not inherited from parent platforms. |
| `parents` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` The label of a `platform` target that this platform should inherit from. Although the attribute takes a list, there should be no more than one platform present. Any constraint\_settings not set directly on this platform will be found in the parent platform. See the section on [Platform Inheritance](#platform_inheritance) for details. |
| `required_settings` | List of [labels](/concepts/labels); default is `[]` A list of `config_setting`s that must be satisfied by the target configuration in order for this platform to be used as an execution platform during toolchain resolution. Required settings are not inherited from parent platforms. |
## toolchain
[View rule source](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/platform/ToolchainRule.java)
```
toolchain(name, aspect_hints, deprecation, exec_compatible_with, features, licenses, package_metadata, tags, target_compatible_with, target_settings, testonly, toolchain, toolchain_type, use_target_platform_constraints, visibility)
```
This rule declares a specific toolchain's type and constraints so that it can be selected
during toolchain resolution. See the
[Toolchains](https://bazel.build/docs/toolchains) page for more
details.
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `exec_compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` A list of `constraint_value`s that must be satisfied by an execution platform in order for this toolchain to be selected for a target building on that platform. |
| `target_compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); default is `[]` A list of `constraint_value`s that must be satisfied by the target platform in order for this toolchain to be selected for a target building for that platform. |
| `target_settings` | List of [labels](/concepts/labels); default is `[]` A list of `config_setting`s that must be satisfied by the target configuration in order for this toolchain to be selected during toolchain resolution. |
| `toolchain` | [Name](/concepts/labels#target-names); required The target representing the actual tool or tool suite that is made available when this toolchain is selected. |
| `toolchain_type` | [Label](/concepts/labels); [nonconfigurable](common-definitions#configurable-attributes); required The label of a `toolchain_type` target that represents the role that this toolchain serves. |
| `use_target_platform_constraints` | Boolean; [nonconfigurable](common-definitions#configurable-attributes); default is `False` If `True`, this toolchain behaves as if its `exec_compatible_with` and `target_compatible_with` constraints are set to those of the current target platform. `exec_compatible_with` and `target_compatible_with` must not be set in that case. |
## toolchain\_type
[View rule source](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/ToolchainType.java)
```
toolchain_type(name, aspect_hints, compatible_with, deprecation, features, no_match_error, package_metadata, restricted_to, tags, target_compatible_with, testonly, visibility)
```
This rule defines a new type of toolchain -- a simple target that represents a class of tools that
serve the same role for different platforms.
See the [Toolchains](/docs/toolchains) page for more details.
#### Example
This defines a toolchain type for a custom rule.
```
toolchain_type(
name = "bar_toolchain_type",
)
```
This can be used in a bzl file.
```
bar_binary = rule(
implementation = _bar_binary_impl,
attrs = {
"srcs": attr.label_list(allow_files = True),
...
# No `_compiler` attribute anymore.
},
toolchains = ["//bar_tools:toolchain_type"]
)
```
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `no_match_error` | String; [nonconfigurable](common-definitions#configurable-attributes); default is `""` A custom error message to display when no matching toolchain is found for this type. |
# Command line reference
Source: https://bazel.build/reference/command-line-reference
## Commands
| | |
| - | - |
| [`aquery`](#aquery) | Analyzes the given targets and queries the action graph. |
| [`build`](#build) | Builds the specified targets. |
| [`canonicalize-flags`](#canonicalize-flags) | Canonicalizes a list of bazel options. |
| [`clean`](#clean) | Removes output files and optionally stops the server. |
| [`coverage`](#coverage) | Generates code coverage report for specified test targets. |
| [`cquery`](#cquery) | Loads, analyzes, and queries the specified targets w/ configurations. |
| [`dump`](#dump) | Dumps the internal state of the bazel server process. |
| [`fetch`](#fetch) | Fetches external repositories that are prerequisites to the targets. |
| [`help`](#help) | Prints help for commands, or the index. |
| [`info`](#info) | Displays runtime info about the bazel server. |
| [`license`](#license) | Prints the license of this software. |
| [`mobile-install`](#mobile-install) | Installs targets to mobile devices. |
| [`mod`](#mod) | Queries the Bzlmod external dependency graph |
| [`print_action`](#print_action) | Prints the command line args for compiling a file. |
| [`query`](#query) | Executes a dependency graph query. |
| [`run`](#run) | Runs the specified target. |
| [`shutdown`](#shutdown) | Stops the bazel server. |
| [`test`](#test) | Builds and runs the specified test targets. |
| [`vendor`](#vendor) | Fetches external repositories into a folder specified by the flag --vendor\_dir. |
| [`version`](#version) | Prints version information for bazel. |
## Startup Options
Options that appear before the command and are parsed by the client
When --noautodetect\_server\_javabase is passed, Bazel does not fall back to the local JDK for running the bazel server and instead exits.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
If set, Bazel will be run as just a client process without a server, instead of in the standard client/server mode. This is deprecated and will be removed, please prefer shutting down the server explicitly if you wish to avoid lingering servers.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`deprecated`](#metadata_tag_DEPRECATED)
Only on Linux; use 'batch' CPU scheduling for Blaze. This policy is useful for workloads that are non-interactive, but do not want to lower their nice value. See 'man 2 sched\_setscheduler'. If false, then Bazel does not perform a system call.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The location of the user .bazelrc file containing default values of Bazel options.
`/dev/null` indicates that all further `--bazelrc`s will be ignored, which is useful to
disable the search for a user rc file, e.g. in release builds.
This option can also be specified multiple times. e.g. with
`--bazelrc=x.rc --bazelrc=y.rc --bazelrc=/dev/null --bazelrc=z.rc`.
* `x.rc` and `y.rc` are read.
* `z.rc` is ignored due to the prior `/dev/null`.
If unspecified, Bazel uses the first `.bazelrc` file it finds in
the following two locations: the workspace directory, then the user's home
directory.
Note: command line options will always supersede any option in bazelrc.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
When --noblock\_for\_lock is passed, Bazel does not wait for a running command to complete, but instead exits immediately. If a duration is specified (e.g. --block\_for\_lock=30s), Bazel will wait up to that duration for the lock before exiting.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If true, log debug information from the client to stderr. Changing this option will not cause the server to restart.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
The amount of time the client waits for each attempt to connect to the server
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
If true, the server will delete its output base directory upon shutting down (whether via explicit shutdown, idle timeout, low memory, or batch mode completion). Only supported on local filesystems; network filesystems (such as NFS) are not supported.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
The hash function to use when computing file digests.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
The cgroup where to start the bazel server as an absolute path. The server process will be started in the specified cgroup for each supported controller. For example, if the value of this flag is /build/bazel and the cpu and memory controllers are mounted respectively on /sys/fs/cgroup/cpu and /sys/fs/cgroup/memory, the server will be started in the cgroups /sys/fs/cgroup/cpu/build/bazel and /sys/fs/cgroup/memory/build/bazel.It is not an error if the specified cgroup is not writable for one or more of the controllers. This options does not have any effect on platforms that do not support cgroups.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING), [`execution`](#effect_tag_EXECUTION)
If true, the Bazel server will be run with systemd-run, and the user will own the cgroup. This flag only takes effect on Linux.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING), [`execution`](#effect_tag_EXECUTION)
Use compact object headers in the JVM. Enabled by default for Bazel when using the embedded JDK. This can reduce memory usage by 5-7%.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
A colon-separated list of classpath entries to be added to the classpath of the Bazel server.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
If set, specifies a location to write a failure\_detail protobuf message if the server experiences a failure and cannot report it via gRPC, as normal. Otherwise, the location will be \$\{OUTPUT\_BASE}/failure\_detail.rawproto.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Whether or not to look for the home bazelrc file at `$HOME/.bazelrc`
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Run System.gc() when the server is idle
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Disables all rc files, regardless of the values of other rc-modifying flags, even if these flags come later in the list of startup options.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Only on Linux; set a level from 0-7 for best-effort IO scheduling using the sys\_ioprio\_set system call. 0 is highest priority, 7 is lowest. The anticipatory scheduler may only honor up to priority 4. If set to a negative value, then Bazel does not perform a system call.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The maximum amount of time the client waits to connect to the server
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Sets the QoS service class of the bazel server when running on macOS. This flag has no effect on all other platforms but is supported to ensure rc files can be shared among them without changes. Possible values are: default (leave QoS unchanged), utility, and background. Only utility and background request a macOS process QoS class because Apple's posix\_spawnattr\_set\_qos\_class\_np API does not accept user-interactive or user-initiated for spawned processes.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The number of seconds the build server will wait idling before shutting down. Zero means that the server will never shutdown. This is only read on server-startup, changing this option will not cause the server to restart.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
If set, specifies the output location to which all build output will be written. Otherwise, the location will be \$\{OUTPUT\_ROOT}/*blaze*\$\{USER}/\$\{MD5\_OF\_WORKSPACE\_ROOT}. Note: If you specify a different option from one to the next Bazel invocation for this value, you'll likely start up a new, additional Bazel server. Bazel starts exactly one server per specified output base. Typically there is one output base per workspace - however, with this option you may have multiple output bases per workspace and thereby run multiple builds for the same client on the same machine concurrently. See 'bazel help shutdown' on how to shutdown a Bazel server.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
The user-specific directory beneath which all build outputs are written; by default, this is a function of \$USER, but by specifying a constant, build outputs can be shared between collaborating users.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
If true, the command can be preempted if another command is started.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If true, no informational messages are emitted on the console, only errors. Changing this option will not cause the server to restart.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
The location to write the server's JVM's output. If unset then defaults to a location in output\_base.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
If max\_idle\_secs is set and the build server has been idle for at least 5 minutes, shut down the server when available system memory falls below critical thresholds. Linux and macOS only.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Whether or not to look for the system-wide bazelrc.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Raises the soft coredump limit to the hard limit to make coredumps of the server (including the JVM) and the client possible under common conditions. Stick this flag in your bazelrc once and forget about it so that you get coredumps when you actually encounter a condition that triggers them.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
If true, real symbolic links will be created on Windows instead of file copying. Requires Windows developer mode to be enabled and Windows 10 version 1703 or greater.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Whether or not to look for the workspace bazelrc file at `$workspace/.bazelrc`
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Remote caching and execution options
If enabled, the remote cache will be used to store the results of reproducible repository
rules. If a repository rule needs to be evaluated and its result is already in the remote
cache, the contents of the repository will be kept in an in-memory file system and are
only downloaded when needed, either by Bazel itself or an action that runs locally.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Miscellaneous options, not otherwise categorized.
Flags to pass to the JVM executing Blaze.
*May be used multiple times; values are accumulated.*
Convenience option to add some additional JVM startup flags, which cause the JVM to wait during startup until you connect from a JDWP-compliant debugger (like Eclipse) to port 5005.
Expands to:
* `--host_jvm_args=-agentlib:jdwp=transport=dt_socket,server=y,address=5005`
Path to the JVM used to execute Bazel itself.
## Options Common to all Commands
Options that appear before the command and are parsed by the client
Additional places to search for archives before accessing the network to download them.
*May be used multiple times; values are accumulated.*
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
If set, the repository cache will hardlink the file in case of a cache hit, rather than copying. This is intended to save disk space.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
The maximum number of attempts to retry a download error. If set to 0, retries are disabled.
Tags: [`experimental`](#metadata_tag_EXPERIMENTAL)
Scale all timeouts in Starlark repository rules by this factor. In this way, external repositories can be made working on machines that are slower than the rule author expected, without changing the source code
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`experimental`](#metadata_tag_EXPERIMENTAL)
The maximum number of attempts for http downloads.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
The maximum timeout for http download retries. With a value of 0, no timeout maximum is defined.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
The maximum number parallel http downloads.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Scale all timeouts related to http downloads by the given factor
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Specifies the location of the repo contents cache, which contains fetched repo
directories shareable across workspaces. An empty string as argument requests the repo
contents cache to be disabled, otherwise the default of `{--repository_cache}/contents`
is used. Note that this means setting `--repository_cache=` would by default disable the
repo contents cache as well, unless `--repo_contents_cache={some_path}` is also set.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Specifies the amount of time the server must remain idle before garbage collection happens
to the repo contents cache.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Specifies the amount of time an entry in the repo contents cache can stay unused before
it's garbage collected. If set to zero, only duplicate entries will be garbage collected.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Specifies the cache location of the downloaded values obtained
during the fetching of external repositories. An empty string
as argument requests the cache to be disabled,
otherwise the default of `{--output_user_root}/cache/repos/v1` is used.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
If set, downloading using `ctx.download{,_and_extract}` is not allowed during repository
fetching. Note that network access is not completely disabled; ctx.execute could
still run an arbitrary executable that accesses the Internet.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Options that control build execution
The maximum size of the stdout / stderr files that will be printed to the console. -1 implies no limit.
Tags: [`execution`](#effect_tag_EXECUTION)
At any point after an invocation has been running for at least one minute, if Blaze has spent at least this percentage of the invocation's wall time doing full GCs, Blaze will give up and fail with an OOM. A value of 100 effectively means to never give up for this reason.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If set to a value in \[0, 100] and this is a command that takes top-level targets (e.g. build but not query) and there are multiple such top-level targets, overrides --gc\_churning\_threshold. Useful to configure more aggressive OOMing behavior (i.e. a lower value than --gc\_churning\_threshold) when they are multiple top-level targets so that the invoker of Bazel can split and retry while still having less aggressive behavior when there is a single top-level target.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The percent of tenured space occupied (0-100) above which GcThrashingDetector considers memory pressure events against its limits (--gc\_thrashing\_limits). If set to 100, GcThrashingDetector is disabled.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Options that configure the toolchain used for action execution
If true, proto lang rules define toolchains from protobuf repository.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Maximum number of open files allowed during BEP artifact upload.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, repository rules and module extensions will only inherit `PATH`, `PATHEXT`
(on Windows), and environment variables explicitly specified by `--repo_env`.
Note that unless `--incompatible_repo_env_ignores_action_env` is true,
`--action_env=NAME=VALUE` will also be included.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, `--action_env=NAME=VALUE` will no longer affect repository rule and module extension environments.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Downloads all remote outputs to the local machine. This flag is an alias for --remote\_download\_outputs=all.
Expands to:
* `--remote_download_outputs=all`
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Does not download any remote build outputs to the local machine. This flag is an alias for --remote\_download\_outputs=minimal.
Expands to:
* `--remote_download_outputs=minimal`
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set to 'minimal' doesn't download any remote build outputs to the local machine, except the ones required by local actions. If set to 'toplevel' behaves like 'minimal' except that it also downloads outputs of top level targets to the local machine. Both options can significantly reduce build times if network bandwidth is a bottleneck.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Instead of downloading remote build outputs to the local machine, create symbolic links. The target of the symbolic links can be specified in the form of a template string. This template string may contain \{hash} and \{size\_bytes} that expand to the hash of the object and the size in bytes, respectively. These symbolic links may, for example, point to a FUSE file system that loads objects from the CAS on demand.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Only downloads remote outputs of top level targets to the local machine. This flag is an alias for --remote\_download\_outputs=toplevel.
Expands to:
* `--remote_download_outputs=toplevel`
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies additional environment variables to be available only for repository rules. Note that repository rules see the full environment anyway, but in this way variables can be set via command-line flags and `.bazelrc` entries. The special syntax `=NAME` can be used to explicitly unset a variable. The string `%bazel_workspace%` in a value will be replaced with the absolute path of the workspace as printed by `bazel info workspace`.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If enabled, issue only a warning instead of an error for loads of experimental .bzls.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If disabled, .bzl load visibility errors are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If enabled (or set to 'error'), fail if Starlark files are not UTF-8 encoded. If set to 'warning', emit a warning instead. If set to 'off', Bazel assumes that Starlark files are UTF-8 encoded but does not verify this assumption. Note that Starlark files which are not UTF-8 encoded can cause Bazel to behave inconsistently.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
A label to a .scl file defining an ALLOWED list of .bzl/.scl file paths exempt from file size limits.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If enabled, adds a `visibility()` function that .bzl files may call during top-level evaluation to set their visibility for the purpose of load() statements.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set to true, rule attributes and Starlark API methods needed for the rule cc\_shared\_library will be available
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set to true, attr.label(materializer=), attr(for\_dependency\_resolution=), attr.dormant\_label(), attr.dormant\_label\_list() and rule(for\_dependency\_resolution=) are allowed.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set to true, enables the APIs required to support the Android Starlark migration.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If set to true, enables the `macro()` construct for defining symbolic macros.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable the set data type and set() constructor in Starlark.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set to true, exposes a number of experimental pieces of Starlark build API pertaining to Google legacy code.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, enables the `isolate` parameter in the `use_extension` function.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set to true, enables a number of platform-related Starlark APIs useful for debugging.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set to true, repository\_rule gains some remote execution capabilities.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true enables the repository\_ctx `load_wasm` and `execute_wasm` methods.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true enables compilation of WebAssembly modules.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, the register\_toolchain function may not include target patterns which may refer to more than one package.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Enables dynamic type checking of arguments and return values for functions that contain type annotations or related syntax.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables static type checking in files and functions that contain type annotations or related syntax.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables both static and dynamic type checking in files and functions that contain type annotations or related syntax. This is an expansion flag for --experimental\_starlark\_static\_type\_checking and --experimental\_starlark\_dynamic\_type\_checking. (When both flags are disabled, Bazel is more forgiving of invalid types in type annotations.)
Expands to:
* `--experimental_starlark_static_type_checking`
* `--experimental_starlark_dynamic_type_checking`
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables type annotations and related syntax in .bzl files. Locations of files where these are allowed is further restricted by `--experimental_starlark_types_allowed_paths`.
Type syntax is never permitted in .scl files regardless of this flag.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
List of canonical Label prefixes under which Starlark type annotations are allowed.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If --force\_starlark\_stack\_trace=true, Starlark stace traces will always be printed from calls to fail(), including those normally supressed with fail(..., stack\_trace = False)
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set to true, tags will be propagated from a target to the actions' execution requirements; otherwise tags are not propagated. See [https://github.com/bazelbuild/bazel/issues/8830](https://github.com/bazelbuild/bazel/issues/8830) for details.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Check the validity of elements added to depsets, in all constructors. Elements must be immutable, but historically the depset(direct=...) constructor forgot to check. Use tuples instead of lists in depset elements. See [https://github.com/bazelbuild/bazel/issues/10313](https://github.com/bazelbuild/bazel/issues/10313) for details.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, a source directory in an external repository fails the build if it crosses a package boundary into a sub-package, matching the behavior that already applies to source directories in the main repository. If false, such package boundary crossings inside external repositories are not detected.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Disable objc\_library's custom transition and inherit from the top level target instead (No-op in Bazel)
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, rule attributes cannot set 'cfg = "host"'. Rules should set 'cfg = "exec"' instead.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, disable the ability to utilize the default provider via field syntax. Use provider-key syntax instead. For example, instead of using `ctx.attr.dep.files` to access `files`, utilize \`ctx.attr.dep\[DefaultInfo].files See [https://github.com/bazelbuild/bazel/issues/9014](https://github.com/bazelbuild/bazel/issues/9014) for details.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
A comma-separated list of flags that cannot be used in transitions inputs or outputs.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If set to true, calling the deprecated ctx.resolve\_tools API always fails. Uses of this API should be replaced by an executable or tools argument to ctx.actions.run or ctx.actions.run\_shell.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, the default value of the `allow_empty` argument of glob() is False.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, certain deprecated APIs (native.repository\_name, Label.workspace\_name, Label.workspace\_root, Label.relative) can be used.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If enabled, targets that have unknown attributes set to None fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
In package\_group's `packages` attribute, changes the meaning of the value "//..." to refer to all packages in the current repository instead of all packages in any repository. You can use the special value "public" in place of "//..." to obtain the old behavior. This flag requires that --incompatible\_package\_group\_has\_public\_syntax also be enabled.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Whether a target that provides an executable expands to the executable rather than the files in `DefaultInfo.files` under \$(locations ...) expansion if the number of files is not 1.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, disables the function `attr.license`.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set, (used) source files are package private unless exported explicitly. See [https://github.com/bazelbuild/proposals/blob/master/designs/2019-10-24-file-visibility.md](https://github.com/bazelbuild/proposals/blob/master/designs/2019-10-24-file-visibility.md)
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, then methods on `repository_ctx` that are passed a Label will no longer automatically watch the file under that label for changes even if `watch = "no"`, and `repository_ctx.path` no longer causes the returned path to be watched. Use `repository_ctx.watch` instead.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, disables the `outputs` parameter of the `rule()` Starlark function.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
In package\_group's `packages` attribute, allows writing "public" or "private" to refer to all packages or no packages respectively.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, targets in the aspect\_hints attribute must satisfy the providers required by at least one aspect's required\_aspect\_hints\_providers. That is, for each target C in a target P's aspect\_hints attribute, C will be made a dependency of P only if there is at least one aspect A being applied to P where C's rule class declares providers that satifies A's required\_aspect\_hints\_providers.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, ctx.actions.run and ctx.actions.run\_shell will require an explicit mnemonic.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, string keys in dicts passed to select() in .bzl files are immediately resolved to Labels relative to the file instead of being interpreted relative to the BUILD file they are ultimately loaded from.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, the command parameter of actions.run\_shell will only accept string
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, simplify configurable rule attributes which contain only unconditional selects; for example, if \["a"] + select("//conditions:default", \["b"]) is assigned to a rule attribute, it is stored as \["a", "b"]. This option does not affect attributes of symbolic macros or attribute default values.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set to true, deprecated ctx.build\_file\_path will not be available. ctx.label.package + '/BUILD' can be used instead.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, invalid attribute values in symbolic macros are treated as an error and fail the build, matching the behavior of rules.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When true, Bazel will stringify the label @//foo:bar to @//foo:bar, instead of //foo:bar. This only affects the behavior of str(), the % operator, and so on; the behavior of repr() is unchanged. See [https://github.com/bazelbuild/bazel/issues/15916](https://github.com/bazelbuild/bazel/issues/15916) for more information.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
The hard maximum size in bytes allowed for an individual .bzl or .scl file. Files exceeding this size fail compilation unless on --bzl\_file\_size\_limit\_allowlist (zero means no limit).
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
The maximum number of Starlark computation steps that may be executed by a BUILD file (zero means no limit).
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
The maximum depth of the graph internal to a depset (also known as NestedSet), above which the depset() constructor will fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
The soft maximum size in bytes for an individual .bzl or .scl file. Files exceeding this size fail compilation unless they define \_KNOWN\_OVERSIZED\_BZL\_FILE at the top level or are on --bzl\_file\_size\_limit\_allowlist (zero means no limit).
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Options relating to Bzlmod output and semantics
Specified the module versions in the form of
`{module1}@{version1},module2@{version2}` that will be allowed in the resolved
dependency graph even if they are declared yanked in the registry where they come
from (if they are not coming from a `NonRegistryOverride`).
Otherwise, yanked versions will cause the resolution to fail. You can also define allowed
yanked versions with the `BZLMOD_ALLOW_YANKED_VERSIONS` environment variable. You can
disable this check by using the keyword `all` (not recommended).
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Check bazel version compatibility of Bazel modules. Valid values are `error` to escalate it to a resolution failure, `off` to disable the check, or `warning` to print a warning when mismatch detected.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Check if the direct `bazel_dep` dependencies declared in the root module are the same versions you get in the resolved dependency graph. Valid values are `off` to disable the check, `warning` to print a warning when mismatch detected or `error` to escalate it to a resolution failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If true, Bazel ignores `bazel_dep`, `use_extension`, and `include` declared as
`dev_dependency` in the `MODULE.bazel` of the root module. Note that these dev
dependencies are always ignored in the `MODULE.bazel` if it is not the root module,
regardless of the value of this flag.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Require repository rules and module extensions to return explicit metadata. Valid values are `false` to disable the check, `all` to require metadata everywhere, or `root` to require metadata only for repo rules and extensions defined in the root module.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Specifies how and whether or not to use the lockfile. Valid values are `update` to use the lockfile and update it if there are changes, `refresh` to additionally refresh mutable information (yanked versions and previously missing modules) from remote registries from time to time, `error` to use the lockfile but throw an error if needed information is not up-to-date (superfluous entries that the current resolution does not consult are ignored, not reported), or `off` to neither read from or write to the lockfile.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies URLs under which the source URLs of Bazel modules can be found, in addition
to and taking precedence over any registry-provided mirror URLs. This flag can be
specified per-registry using the syntax
`--module_mirrors==[,,...]` (e.g.,
`--module_mirrors=https://bcr.bazel.build=https://mirror.example.com`). It can also
be specified as a comma-separated list of mirror URLs that applies to all registries that
don't have an explicit list (e.g., `--module_mirrors=https://mirror1,https://mirror2`).
Set this to an empty value to disable the use of any mirrors not specified by the
registries. Later uses of this flag override earlier ones with the same (or no) registry.
The default set of mirrors may change over time, but all downloads from mirrors are
verified by hashes stored in the registry (and thus pinned by the lockfile).
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Override a module with a local path in the form of `{module name}={path}`. If the given
path is an absolute path, it will be used as it is. If the given path is a
relative path, it is relative to the current working directory. If the given path
starts with `%workspace%`, it is relative to the workspace root, which is the
output of `bazel info workspace`. If the given path is empty, then remove any
previous overrides.
*May be used multiple times; values are accumulated.*
Specifies the registries to use to locate Bazel module dependencies. The order is important: modules will be looked up in earlier registries first, and only fall back to later registries when they're missing from the earlier ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Specifies the directory that should hold the external repositories in vendor mode, whether for the purpose of fetching them into it or using them while building. The path can be specified as either an absolute path or a path relative to the workspace directory.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that trigger optimizations of the build time
Whether to enable memory optimizations that may be non-deterministic with respect to their efficacy. Enable this to use less memory; disable this for more consistent memory measurements
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Limits which, if reached, cause GcThrashingDetector to crash Bazel with an OOM. Each limit is specified as \:\ where period is a duration and count is a positive integer. If more than --gc\_thrashing\_threshold percent of tenured space (old gen heap) remains occupied after \ consecutive full GCs within \, an OOM is triggered. Multiple limits can be specified separated by commas.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If true, Bazel will remove FileState and DirectoryListingState nodes after related File and DirectoryListing node is done to save memory. We expect that it is less likely that these nodes will be needed again. If so, the program will re-evaluate them.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
If false, Blaze will discard the inmemory state from this build when the build finishes. Subsequent builds will not have any incrementality with respect to this one.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Flag for advanced configuration of Bazel's internal Skyframe engine. If Bazel detects its retained heap percentage usage exceeds the threshold set by --skyframe\_high\_water\_mark\_threshold, when a full GC event occurs, it will drop unnecessary temporary Skyframe state, up to this many times per invocation. Defaults to 10. Zero means that full GC events will never trigger drops. If the limit is reached, Skyframe state will no longer be dropped when a full GC event occurs and that retained heap percentage threshold is exceeded.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Flag for advanced configuration of Bazel's internal Skyframe engine. If Bazel detects its retained heap percentage usage exceeds the threshold set by --skyframe\_high\_water\_mark\_threshold, when a minor GC event occurs, it will drop unnecessary temporary Skyframe state, up to this many times per invocation. Defaults to 10. Zero means that minor GC events will never trigger drops. If the limit is reached, Skyframe state will no longer be dropped when a minor GC event occurs and that retained heap percentage threshold is exceeded.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Flag for advanced configuration of Bazel's internal Skyframe engine. If Bazel detects its retained heap percentage usage is at least this threshold, it will drop unnecessary temporary Skyframe state. Tweaking this may let you mitigate wall time impact of GC thrashing, when the GC thrashing is (i) caused by the memory usage of this temporary state and (ii) more costly than reconstituting the state when it is needed.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If false, Bazel will not persist data that allows for invalidation and re-evaluation on incremental builds in order to save memory on this build. Subsequent builds will not have any incrementality with respect to this one. Usually you will want to specify --batch when setting this to false.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Options that affect the verbosity, format or location of logging
Whether to announce rc options.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When printing the location part of messages, attempt to use a path relative to the workspace directory or one of the directories specified by --package\_path.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Specifies the build event service (BES) backend endpoint in the form
`[SCHEME://]HOST[:PORT]`. The default is to disable BES uploads. Supported schemes
are `grpc` and `grpcs` (grpc with TLS enabled). If no scheme is provided, Bazel
assumes `grpcs`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the field `check_preceding_lifecycle_events_present` on
`PublishBuildToolEventStreamRequest` which tells BES to check whether it previously
received `InvocationAttemptStarted` and `BuildEnqueued` events matching the current
tool event.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specify a header in `NAME=VALUE` form that will be included in BES requests.
Multiple headers can be passed by specifying the flag multiple times. Multiple
values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Specifies the instance name under which the BES will persist uploaded BEP. Defaults to null.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a list of notification keywords to be added the default set of keywords
published to BES (`command_name={command_name}`, `protocol_name=BEP`).
Defaults to none.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether to publish BES lifecycle events. (defaults to 'true').
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies how long bazel should wait for the BES/BEP upload to complete while OOMing. This flag ensures termination when the JVM is severely GC thrashing and cannot make progress on any user thread.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Specifies the maximal size of stdout or stderr to be buffered in BEP, before it is
reported as a progress event. Individual writes are still reported in a single
event, even if larger than the specified value up to `--bes_outerr_chunk_size`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the maximal size of stdout or stderr to be sent to BEP in a single message.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Connect to the Build Event Service through a proxy. Currently this flag can only be
used to configure a Unix domain socket (`unix:/path/to/socket`).
Specifies the base URL where a user can view the information streamed to the BES backend. Bazel will output the URL appended by the invocation id to the terminal.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Specifies a list of notification keywords to be included directly, without the
`user_keyword=` prefix included for keywords supplied via `--bes_keywords`.
Intended for Build service operators that set `--bes_lifecycle_events=false` and
include keywords when calling `PublishLifecycleEvent`. Build service operators
using this flag should prevent users from overriding the flag value.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies how long bazel should wait for the BES/BEP upload to complete after the
build and tests have finished. A valid timeout is a natural number followed by a
unit: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). The
default value is `0` which means that there is no timeout.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether the Build Event Service upload should block the build completion or
should end the invocation immediately and finish the upload in the
background.
* `wait_for_upload_complete`: blocks at the end of the current invocation until
all events (including lifecycle events if applicable) are uploaded and
acknowledged by the backend.
* `nowait_for_upload_complete`: blocks at the beginning of the next invocation
until all events (including lifecycle events if applicable) are uploaded and
acknowledged by the backend.
* `fully_async`: blocks at the beginning of the next invocation until all events
are uploaded but does not wait for acknowledgements. Events may be lost in case
of (transient) failures and backends may report streams as incomplete in this
mode. There is no guarantee that `FinishInvocationAttempt` or `FinishBuild`
lifecycle events are sent.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If non-empty, write a varint delimited binary representation of representation of the
build event protocol to that file. This option implies
`--bes_upload_mode=wait_for_upload_complete`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Convert paths in the binary file representation of the build event protocol to more
globally valid URIs whenever possible; if disabled, the `file://` uri scheme will
always be used
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether the Build Event Service upload for `--build_event_binary_file` should
block the build completion or should end the invocation immediately and finish
the upload in the background. Either `wait_for_upload_complete` (default),
`nowait_for_upload_complete`, or `fully_async`.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If non-empty, write a JSON serialisation of the build event protocol to that file.
This option implies `--bes_upload_mode=wait_for_upload_complete`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Convert paths in the json file representation of the build event protocol to more
globally valid URIs whenever possible; if disabled, the `file://` uri scheme will
always be used
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether the Build Event Service upload for `--build_event_json_file` should
block the build completion or should end the invocation immediately and finish
the upload in the background. Either `wait_for_upload_complete` (default),
`nowait_for_upload_complete`, or `fully_async`.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
The maximum number of entries for a single `named_set_of_files` event; values smaller
than 2 are ignored and no event splitting is performed. This is intended for
limiting the maximum event size in the build event protocol, although it does not
directly control event size. The total event size is a function of the structure
of the set as well as the file and uri lengths, which may in turn depend on the
hash function.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether all actions should be published.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If non-empty, write a textual representation of the build event protocol to that file
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Convert paths in the text file representation of the build event protocol to more
globally valid URIs whenever possible; if disabled, the `file://` uri scheme will
always be used
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether the Build Event Service upload for `--build_event_text_file` should
block the build completion or should end the invocation immediately and finish
the upload in the background. Either `wait_for_upload_complete` (default),
`nowait_for_upload_complete`, or `fully_async`.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
The maximum number of times Bazel should retry uploading a build event.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Whether to publish `TargetSummary` events.
No-op.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specify how an output group's files will be represented in `TargetComplete`/`AspectComplete`
BEP events. Values are an assignment of an output group name to one of
`NAMED_SET_OF_FILES_ONLY`, `INLINE_ONLY`, or `BOTH`. The default value is
`NAMED_SET_OF_FILES_ONLY`. If an output group is repeated, the final value to
appear is used. The default value sets the mode for coverage artifacts to BOTH:
`--experimental_build_event_output_group_mode=baseline.lcov=both`
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Initial, minimum delay for exponential backoff retries when BEP upload fails. (exponent: 1.6)
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Selects how to upload artifacts referenced in the build event protocol. In Bazel
the valid options include `local` and `remote`. The default value is `local`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, the profiler collects the system's overall load average.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If enabled, the profiler collects the Linux PSI data.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If enabled, the profiler collects CPU and memory usage estimation for local actions.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If enabled, the profiler collects SkyFunction counts in the Skyframe graph over time for key function types, like configured targets and action executions. May have a performance hit as this visits the ENTIRE Skyframe graph at every profiling time unit. Do not use this flag with performance-critical measurements.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If enabled, the profiler collects the system's network usage.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If enabled, the profiler collects worker's aggregated resource data.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Records a Java Flight Recorder profile for the duration of the command. One of the supported profiling event types (cpu, wall, alloc or lock) must be given as an argument. The profile is written to a file named after the event type under the output base directory. The syntax and semantics of this flag might change in the future to support additional profile types or output formats; use at your own risk.
If set, wait for the Build Event Service event queue to quiesce before taking memory profile measurements at the end of the build. Ignored if --memory\_profile is not set.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Specifies additional profile tasks to be included in the profile.
*May be used multiple times; values are accumulated.*
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Includes the extra "out" attribute in action and critical-path events that contains the exec path to the action's primary output.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Includes target configuration hash in action and critical-path events' JSON profile data.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Includes target label in action and critical-path events' JSON profile data.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Controls the output of BEP ActionSummary and BuildGraphMetrics, limiting the number of mnemonics in ActionData and number of entries reported in BuildGraphMetrics.AspectCount/RuleClassCount. By default the number of types is limited to the top 20, by number of executed actions for ActionData, and instances for RuleClass and Asepcts. Setting this option will write statistics for all mnemonics, rule classes and aspects.
Controls the output of BEP BuildGraphMetrics, including expensive to compute skyframe metrics about Skykeys, RuleClasses and Aspects. With this flag set to false BuildGraphMetrics.rule\_count and aspect fields will not be populated in the BEP.
Whether to include the command-line residue in run build events which could contain the residue. By default, the residue is not included in run command build events that could contain the residue.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Stream log file uploads directly to the remote storage rather than writing them to disk.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Log certain Workspace Rules events into this file as delimited WorkspaceEvent protos.
If enabled, Bazel profiles the build and writes a JSON-format profile into a file in the output base. View profile by loading into chrome://tracing. By default Bazel writes the profile for all build-like commands and query.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Whether to manually output a heap dump if an OOM is thrown (including manual OOMs due to reaching --gc\_thrashing\_limits). The dump will be written to \
Regex for overriding the matching logic for JDK21+ JVM heap memory collection. We are relying on volatile internal G1 GC implemenation details to get a clean memory metric, this option allows us to adapt to changes in that internal implementation without having to wait for a binary release. Passed to JDK Matcher.find()
Use this to suppress generation of the legacy `important_outputs` field in the
`TargetComplete` event. `important_outputs` are required for Bazel to ResultStore/BTX
integration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The logging level.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, write memory usage data to the specified file at phase ends and stable heap to master log at end of build.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Tune memory profile's computation of stable heap at end of build. Should be and even number of integers separated by commas. In each pair the first integer is the number of GCs to perform. The second integer in each pair is the number of seconds to wait between GCs. Ex: 2,4,4,0 would 2 GCs with a 4sec pause, followed by 4 GCs with zero second pause
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If set, profile Bazel and write data to the specified file. See [https://bazel.build/advanced/performance/json-trace-profile](https://bazel.build/advanced/performance/json-trace-profile) for more information.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Number of profiles to retain in the output base. If there are more than this number of profiles in the output base, the oldest are deleted until the total is under the limit.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
By default, Bazel profiler will record only aggregated data for fast but numerous events (such as statting the file). If this option is enabled, profiler will record each event - resulting in more precise profiling data but LARGE performance hit. Option only has effect if --profile used as well.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If true and supported, instrumentation output is redirected to be written locally on a different machine than where bazel is running on.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Choose when to print remote execution messages. Valid values are `failure`, to print only on failures, `success` to print only on successes and `all` to print always.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Slims down the size of the JSON profile by merging events if the profile gets too large. Supports boolean values or a size in bytes (e.g. 5M) to start slimming after the profile exceeds that size.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Writes into the specified file a pprof profile of CPU usage by all Starlark threads.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If true (or auto with color enabled and a tty), format terminal file paths, test logs, and build results URLs as clickable OSC 8 hyperlinks.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
A tool name to attribute this Bazel invocation to.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Specifies which events to show in the UI. It is possible to add or remove events to the default ones using leading +/-, or override the default set completely with direct assignment. The set of supported event kinds include INFO, DEBUG, ERROR and more.
*May be used multiple times; values are accumulated.*
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether or not to write the command.log file
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Remote caching and execution options
Specify a file to configure the remote downloader with.
This file consists of directives, one per line, that adjust how the
Bazel downloader acts. The directives are: `allow`, `block`, `rewrite`,
and `all_blocked_message`. The directives are applied in the order
`rewrite, allow, block`.
Comments are allowed and must be on their own line (no trailing comments)
and preceded by a `#`. Example: `# evil.com is known to host malicious code`
The `allow` and `block` directives take a host name as an argument. For
example: `block mvnrepository.com.example` or `allow github.com.example`. The given host
and all subdomains will be allowed or blocked. Do not include the URL
scheme (`http://` or `https://`). You can block all hosts with the `*`
wildcard: `block *`.
The `rewrite` directive takes two regex patterns: the first to match a URL
and the second to substitute matched URLs with. For example, `rewrite github.com.example/bazel-contrib/rules_python/releases/download/(.*)/(.*) mycorp.example/rules_python_mirror/$1/$2` will cause the downloader
to access `mycorp.example/rules_python_mirror` whenever attempting
to download rules\_python from example.com. The substitute URL supports
back-references starting from `$1`. It is possible for multiple
`rewrite` directives for the same matched URL to be provided, and in
this case multiple URLs will be returned and tried sequentially. Do not
include the URL scheme (`http://` or `https://`) in the patterns.
The `all_blocked_message` directive allows you to customize the message
that is shown when the rewriter is configured to block all URLs for
a particular resource. This directive can only be given once, and the
message must exist on a single line. Example: `all_blocked_message Hey, I think the downloader config is wrong. Bummer!`.
Note that it is not possible to directly block a particular path for
a given host while still allowing other paths on the host. This can be
worked around by rewrite the path to a blocked host:
```
block dummy_host.invalid
rewrite example.com/bar/.* dummy_host.invalid
```
An example config may look like:
```
all_blocked_message See example.com/blocked-bazel-fetches for more information.
block mvnrepository.com.example
block maven-central.storage.googleapis.com.example
# See internal doc id1234 for why gitblit is blocked
block gitblit.github.com.example
rewrite repo.maven.apache.org.example/maven2/(.*) artifacts.mycorp.example/libs-release/$1
# Use our GCS bucket for rules_python
rewrite github.com.example/bazel-contrib/rules_python/releases/download/(.*)/(.*) mycorp.example/rules_python_mirror/$1/$2
```
See also: [Insulating Builds from the Internet](https://bazel.build/external/faq#how-do-i-insulate-my-builds-from-the-internet)
*May be used multiple times; values are accumulated.*
Specifies the strategy for the circuit breaker to use. Available strategies are "failure". On invalid value for the option the behavior same as the option is not set.
Tags: [`execution`](#effect_tag_EXECUTION)
If enabled, large blobs are split into content-defined chunks and uploaded/downloaded in chunks, enabling deduplication across blobs. The server must advertise SplitBlob/SpliceBlob RPCs and the parameters of the chunking function selected by --experimental\_remote\_cache\_chunking\_function in its capabilities.
Tags: [`experimental`](#metadata_tag_EXPERIMENTAL)
The content-defined chunking function used to split large blobs when --experimental\_remote\_cache\_chunking is enabled. If set to 'auto' (the default), the function is negotiated with the server: FastCDC 2020 is used if the server advertises it, otherwise RepMaxCDC. Set to 'fast\_cdc\_2020' or 'rep\_max\_cdc' to require a specific function, in which case the server must advertise the parameters of that function in its capabilities. All clients sharing a cache should use the same function to maximize chunk reuse.
Tags: [`experimental`](#metadata_tag_EXPERIMENTAL)
The minimum blob size required to compress/decompress with zstd. Ineffectual unless --remote\_cache\_compression is set.
If set to true, Bazel will extend the lease for outputs of remote actions during the build by sending `FindMissingBlobs` calls periodically to remote cache. The frequency is based on the value of `--experimental_remote_cache_ttl`.
The guaranteed minimal TTL of blobs in the remote cache after their digests are recently referenced e.g. by an ActionResult or FindMissingBlobs. Bazel does several optimizations based on the blobs' TTL e.g. doesn't repeatedly call GetActionResult in an incremental build. The value should be set slightly less than the real TTL since there is a gap between when the server returns the digests and when Bazel receives them.
Tags: [`execution`](#effect_tag_EXECUTION)
A path to a directory where the corrupted outputs will be captured to. An empty value resets the flag to its default.
The delay after the failure circuit breaker trips before it allows a single trial remote call to probe whether the remote cache/executor has recovered. If the trial succeeds the breaker closes and normal calls resume; otherwise it re-opens and waits again before the next trial. A zero or negative value (the default) disables recovery, so a tripped breaker stays open for the remainder of the build. Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds. Only takes effect with --experimental\_circuit\_breaker\_strategy=failure.
Tags: [`execution`](#effect_tag_EXECUTION)
If set to true, discard in-memory copies of the input root's Merkle tree and associated input mappings during calls to GetActionResult() and Execute(). This reduces memory usage significantly, but does require Bazel to recompute them upon remote cache misses and retries.
Sets the allowed number of failure rate in percentage for a specific time window after which it stops calling to the remote cache/executor. By default the value is 10. Setting this to 0 means no limitation.
Tags: [`execution`](#effect_tag_EXECUTION)
The interval in which the failure rate of the remote requests are computed. On zero or negative value the failure duration is computed the whole duration of the execution.Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds.
Tags: [`execution`](#effect_tag_EXECUTION)
If set to true, Bazel will mark inputs as tool inputs for the remote executor. This can be used to implement remote persistent workers.
The minimum number of remote calls that must be observed within the failure window before the circuit breaker computes the failure rate. The rate is computed (and the breaker may trip) once either this many total calls or --experimental\_remote\_min\_fail\_count\_to\_compute\_failure\_rate failures are observed. Only takes effect with --experimental\_circuit\_breaker\_strategy=failure.
Tags: [`execution`](#effect_tag_EXECUTION)
The minimum number of failed remote calls that must be observed within the failure window before the circuit breaker computes the failure rate. The rate is computed (and the breaker may trip) once either this many failures or --experimental\_remote\_min\_call\_count\_to\_compute\_failure\_rate total calls are observed. Only takes effect with --experimental\_circuit\_breaker\_strategy=failure.
Tags: [`execution`](#effect_tag_EXECUTION)
HOST or HOST:PORT of a remote output service endpoint. The supported schemes are grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. Specify grpc:// or unix: scheme to disable TLS. An empty value resets the flag to its default.
The path under which the contents of output directories managed by the --experimental\_remote\_output\_service are placed. The actual output directory used by a build will be a descendant of this path and determined by the output service.
If set to true, enforce that all actions that can run remotely are cached, or else fail the build. This is useful to troubleshoot non-determinism issues as it allows checking whether actions that should be cached are actually cached without spuriously injecting new results into the cache.
Enables remote cache key scrubbing with the supplied configuration file, which must be a protocol buffer in text format (see src/main/protobuf/remote\_scrubbing.proto).
This feature is intended to facilitate sharing a remote/disk cache between actions executing on different platforms but targeting the same platform. It should be used with extreme care, as improper settings may cause accidental sharing of cache entries and result in incorrect builds.
Scrubbing does not affect how an action is executed, only how its remote/disk cache key is computed for the purpose of retrieving or storing an action result. Scrubbed actions are incompatible with remote execution, and will always be executed locally instead.
Modifying the scrubbing configuration does not invalidate outputs present in the local filesystem or internal caches; a clean build is required to reexecute affected actions.
In order to successfully use this feature, you likely want to set a custom --host\_platform (to normalize output prefixes). An empty value disables scrubbing.
Set this to 'full' to enable checking the ctime of all input files of an action before uploading it to a remote cache. There may be cases where the Linux kernel delays writing of files, which could cause false positives. The default is 'lite', which only checks source files in the main repository. Setting this to 'off' disables all checks. This is not recommended, as the cache may be polluted when a source file is changed while an action that takes it as an input is executing.
Tags: [`execution`](#effect_tag_EXECUTION)
Whether --remote\_local\_fallback applies to --remote\_cache.
Whether to accept remotely cached action results.
If set to 'all', all local outputs referenced by BEP are uploaded to remote cache.
If set to 'minimal', local outputs referenced by BEP are not uploaded to the remote cache, except for files that are important to the consumers of BEP (e.g. test logs and timing profile). bytestream:// scheme is always used for the uri of files even if they are missing from remote cache.
Default to 'minimal'.
The hostname and instance name to be used in bytestream:// URIs that are written into build event streams. This option can be set when builds are performed using a proxy, which causes the values of --remote\_executor and --remote\_instance\_name to no longer correspond to the canonical name of the remote execution service. When not set, it will default to "\$\{hostname}/\$\{instance\_name}". An empty value resets the flag to its default.
A URI of a caching endpoint. The supported schemes are http, https, grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. Specify grpc://, http\:// or unix: scheme to disable TLS. An empty value resets the flag to its default. See [https://bazel.build/remote/caching](https://bazel.build/remote/caching)
If true, uploading of action results to a disk or remote cache will happen in the background instead of blocking the completion of an action. Some actions are incompatible with background uploads, and may still block even when this flag is set.
If enabled, compress/decompress cache blobs with zstd when their size is at least --experimental\_remote\_cache\_compression\_threshold.
Specify a header that will be included in cache requests: --remote\_cache\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Set the default exec properties to be used as the remote execution platform if an execution platform does not already set exec\_properties.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Force remote build outputs whose path matches this pattern to be downloaded, irrespective of --remote\_download\_outputs. Multiple patterns may be specified by repeating this flag.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
A Remote Asset API endpoint URI, to be used as a remote download proxy. The supported schemes are grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. An empty value resets the flag to its default. See: [https://github.com/bazelbuild/remote-apis/blob/master/build/bazel/remote/asset/v1/remote\_asset.proto](https://github.com/bazelbuild/remote-apis/blob/master/build/bazel/remote/asset/v1/remote_asset.proto)
Specify a header that will be included in remote downloader requests: --remote\_downloader\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Whether to fall back to the local downloader if remote downloader fails.
Whether to propagate credentials from netrc and credential helper to the remote downloader server. The server implementation needs to support the new `http_header_url::` qualifier where the `` is a 0-based position of the URL inside the FetchBlobRequest's `uris` field. The URL-specific headers should take precedence over the global headers.
Specify a header that will be included in execution requests: --remote\_exec\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
The relative priority of actions to be executed remotely. The semantics of the particular priority values are server-dependent.
HOST or HOST:PORT of a remote execution endpoint. The supported schemes are grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. Specify grpc:// or unix: scheme to disable TLS. An empty value resets the flag to its default.
The maximum amount of time a remote gRPC download may go without receiving response data before Bazel cancels and retries the download. This applies to ByteStream Read. The value 0 disables the timeout. If the unit is omitted, the value is interpreted as seconds.
If specified, a path to a file to log gRPC call related details. This log consists of a sequence of serialized com.google.devtools.build.lib.remote.logging.RemoteExecutionLog.LogEntry protobufs with each message prefixed by a varint denoting the size of the following serialized protobuf message, as performed by the method LogEntry.writeDelimitedTo(OutputStream).
Path to a gRPC service config JSON file for remote gRPC channels. This replaces the service config Bazel generates from --remote\_timeout. Only a subset of the gRPC service config JSON schema is supported: top-level methodConfig entries with name objects containing service and optional method, plus timeout. Other service config fields are rejected and may be supported in the future.
Specify a header that will be included in requests: --remote\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Value to pass as instance\_name in the remote execution API.
Whether to fall back to standalone local execution strategy if remote execution fails.
Deprecated. See [https://github.com/bazelbuild/bazel/issues/7480](https://github.com/bazelbuild/bazel/issues/7480) for details.
Tags: [`deprecated`](#metadata_tag_DEPRECATED)
Limit the max number of concurrent requests per gRPC connection. By default the value is 100.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Limit the max number of concurrent connections to remote cache/executor. By default the value is 100. Setting this to 0 means no limitation.
For HTTP remote cache, one TCP connection could handle one request at one time, so Bazel could make up to --remote\_max\_connections concurrent requests.
For gRPC remote cache/executor, one gRPC channel could usually handle 100+ concurrent requests (controlled by --remote\_max\_concurrency\_per\_connection), so Bazel could make around `--remote_max_connections * 100` concurrent requests.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Connect to the remote cache through a proxy. Currently this flag can only be used to configure a Unix domain socket (unix:/path/to/socket). An empty value resets the flag to its default.
The relative priority of remote actions to be stored in remote cache. The semantics of the particular priority values are server-dependent.
The maximum number of attempts to retry a transient error. If set to 0, retries are disabled.
The maximum backoff delay between remote retry attempts. Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds.
The maximum amount of time to wait for remote execution and cache calls. For the REST cache, this is both the connect and the read timeout. Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds.
Whether to upload locally executed action results to the remote cache if the remote cache supports it and the user is authorized to do so.
If set to true, Bazel will compute the hash sum of all remote downloads and discard the remotely cached values if they don't match the expected value.
Miscellaneous options, not otherwise categorized.
How long the server must remain idle before a garbage collection of the action cache is attempted. Ineffectual unless --action\_cache\_gc\_max\_age is nonzero.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If set to a nonzero value, the action cache will be periodically garbage collected to remove entries older than this age. Garbage collection occurs in the background once the server has become idle, as determined by the --action\_cache\_gc\_idle\_delay and --action\_cache\_gc\_threshold flags.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The percentage of stale action cache entries required for garbage collection to be triggered. Ineffectual unless --action\_cache\_gc\_max\_age is nonzero.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Custom key-value string pairs to supply in a build event.
*May be used multiple times; values are accumulated.*
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Unique string identifier that groups together a set of invocations that are conceptually
part of the same overall build request. The value is sent over the BES transport envelope
(as `StreamId.build_id`) and remote execution protocol (as
`RequestMetadata.correlated_invocations_id`).
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Use terminal controls to colorize output.
Selects additional config sections from the rc files; for every \, it also pulls in the options from \:\ if such a section exists; if this section doesn't exist in any .rc file, Bazel fails with an error. The config sections and flag combinations they are equivalent to are located in the tools/\*.blazerc config files.
*May be used multiple times; values are accumulated.*
Configures a credential helper conforming to the [Credential Helper Specification](https://github.com/EngFlow/credential-helper-spec)
to use for retrieving authorization credentials for repository
fetching, remote caching and execution, and the build event service.
The path to the credential helper may be absolute, relative to the PATH environment variable,
or %workspace%-relative. The path may be optionally prefixed by a scope followed by an '='.
The scope is a domain name, optionally with a single leading '\*' wildcard component. A helper
applies to URIs matching its scope, with more specific scopes preferred. If a helper has no
scope, it applies to every URI.
Credentials supplied by a helper take precedence over credentials supplied by
`--google_default_credentials`, `--google_credentials`, a `.netrc` file, or the
auth parameter to `repository_ctx.download()` and
`repository_ctx.download_and_extract()`.
May be specified multiple times to set up multiple helpers.
See [Configuring Bazel's Credential Helper - Engflow Blog](https://blog.engflow.com/2023/10/09/configuring-bazels-credential-helper/) for instructions.
*May be used multiple times; values are accumulated.*
How long to cache credentials for if the credential helper doesn't return an expiration time. Changing the value of this flag clears the cache.
Configures the timeout for a credential helper.
Credential helpers failing to respond within this timeout will fail the invocation.
Use terminal cursor controls to minimize scrolling output.
A path to a directory where Bazel can read and write actions and action outputs. If the directory does not exist, it will be created. Use --disk\_cache with no value (or --disk\_cache=true) to use a default location under the output user root (\/cache/disk). Use --nodisk\_cache or --disk\_cache=false to disable.
How long the server must remain idle before a garbage collection of the disk cache occurs. To specify the garbage collection policy, set --disk\_cache\_gc\_max\_size and/or --disk\_cache\_gc\_max\_age.
If set to a positive value, the disk cache will be periodically garbage collected to remove entries older than this age. If set in conjunction with --disk\_cache\_gc\_max\_size, both criteria are applied. Garbage collection occurrs in the background once the server has become idle, as determined by the --disk\_cache\_gc\_idle\_delay flag.
If set to a positive value, the disk cache will be periodically garbage collected to stay under this size. If set in conjunction with --disk\_cache\_gc\_max\_age, both criteria are applied. Garbage collection occurrs in the background once the server has become idle, as determined by the --disk\_cache\_gc\_idle\_delay flag.
If true, Bazel picks up host-OS-specific config lines from bazelrc files. For example, if the host OS is Linux and you run bazel build, Bazel picks up lines starting with build:linux. Supported OS identifiers are linux, macos, windows, freebsd, and openbsd. Enabling this flag is equivalent to using --config=linux on Linux, --config=windows on Windows, etc.
Whether to enable thread dumps. If true, Bazel will dump the state of all threads (including virtual threads) to a file every --experimental\_thread\_dump\_interval, or after action execution being inactive for --experimental\_thread\_dump\_action\_execution\_inactivity\_duration. The dumps will be written to the \
Enable experimental rule extension API and subrule APIs
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Dump the threads when action execution being inactive for this duration. If zero, no thread dumps are written for action execution being inactive.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
How often to dump the threads periodically. If zero, no thread dumps are written periodically.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
If true, experimental Windows support for --watchfs is enabled. Otherwise --watchfsis a non-op on Windows. Make sure to also enable --watchfs.
A comma-separated list of Google Cloud authentication scopes.
Specifies the file to get authentication credentials from. An empty value resets the flag to its default. See [https://cloud.google.com/docs/authentication](https://cloud.google.com/docs/authentication) for details.
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Whether to use 'Google Application Default Credentials' for authentication.
See [Authentication methods at Google - Google Cloud](https://cloud.google.com/docs/authentication) for details.
Disabled by default.
Configures keep-alive pings for outgoing gRPC connections. If this is set, then Bazel
sends pings after this much time of no read operations on the connection, even if
there are no pending gRPC calls. The value 0 disables the keep-alives.
Configures a keep-alive timeout for outgoing gRPC connections. If keep-alive pings are
enabled with `--grpc_keepalive_time`, then Bazel times out a connection if it does
not receive a ping reply after this much time. Times are treated as second
granularity; it is an error to set a value less than one second. If keep-alive
pings are disabled, then this setting is ignored.
Whether to enable TCP keep-alive (the SO\_KEEPALIVE socket option) for outgoing gRPC
connections. This operates at the transport layer and is independent of the
application-level keep-alive pings configured with `--grpc_keepalive_time`. When enabled,
the keep-alive behavior is controlled by `--grpc_tcp_keepalive_time`,
`--grpc_tcp_keepalive_interval` and `--grpc_tcp_keepalive_count`.
When `--grpc_tcp_keepalive` is enabled, the number of unacknowledged TCP keep-alive probes
to send before considering the connection dead (TCP\_KEEPCNT). Has no effect if TCP
keep-alive is disabled.
When `--grpc_tcp_keepalive` is enabled, the amount of time between successive TCP
keep-alive probes (TCP\_KEEPINTVL). Has no effect if TCP keep-alive is disabled.
When `--grpc_tcp_keepalive` is enabled, the amount of idle time on a gRPC connection
before the first TCP keep-alive probe is sent (TCP\_KEEPIDLE). Has no effect if TCP
keep-alive is disabled.
If true, java\_binary is always executable. create\_executable attribute is removed.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Adds a new repository with a local path in the form of `{repository name}={path}`. This
only takes effect with `--enable_bzlmod` and is equivalent to adding a
corresponding `local_repository` to the root module's `MODULE.bazel` file via
`use_repo_rule`. If the given path is an absolute path, it will be used as it is.
If the given path is a relative path, it is relative to the current working
directory. If the given path starts with `%workspace%`, it is relative to the
workspace root, which is the output of `bazel info workspace`. If the given path
is empty, then remove any previous injections.
*May be used multiple times; values are accumulated.*
How long an install base must go unused before it's eligible for garbage collection. If nonzero, the server will attempt to garbage collect other install bases when idle.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Unique identifier, in UUID format, for the command being run. If explicitly specified uniqueness must be ensured by the caller. The UUID is printed to stderr, the BEP and remote execution protocol.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Override a repository with a local path in the form of `{repository name}={path}`,
where the repository name can be either a canonical name or an apparent name from the
point of view of the main repository.
Note that if this is flag is used to override a module's repository, changes to the
MODULE.bazel file will not be effective if the module is obtained from a registry. Use
`--override_module` instead to for that purpose.
If the given path is an absolute path, it will be used as it is. If the given path is a
relative path, it is relative to the current working directory. If the given path starts
with `%workspace%`, it is relative to the workspace root, which is the output of `bazel info workspace`. If the given path is empty, then remove any previous overrides.
*May be used multiple times; values are accumulated.*
Show the command progress in the terminal title. Useful to see what bazel is doing when having multiple terminal tabs.
Display progress messages during a build.
Minimum number of seconds between progress messages in the output.
Include timestamps in messages
Specify a path to a TLS certificate that is trusted to sign server certificates. An empty value resets the flag to its default.
Specify the TLS client certificate to use; you also need to provide a client key to enable client authentication. An empty value resets the flag to its default.
Specify the TLS client key to use; you also need to provide a client certificate to enable client authentication. An empty value resets the flag to its default.
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Number of concurrent actions shown in the detailed progress bar; each action is shown on a separate line. The progress bar always shows at least one one, all numbers less than 1 are mapped to 1.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
On Linux/macOS: If true, bazel tries to use the operating system's file watch service for local changes instead of scanning every file for a change. On Windows: this flag currently is a non-op but can be enabled in conjunction with --experimental\_windows\_watchfs. On any OS: The behavior is undefined if your workspace is on a network file system, and files are edited on a remote machine.
## Aquery Options
Inherits all options from [build](#build).
Options relating to query output and semantics
How to resolve aspect dependencies when the output format is one of \{xml,proto,record}. 'off' means no aspect dependencies are resolved, 'conservative' (the default) means all declared aspect dependencies are added regardless of whether they are given the rule class of direct dependencies, 'precise' means that only those aspects are added that are possibly active given the rule class of the direct dependencies. Note that precise mode requires loading other packages to evaluate a single target thus making it slower than the other modes. Also note that even precise mode is not completely precise: the decision whether to compute an aspect is decided in the analysis phase, which is not run during 'bazel query'.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If enabled, every query command emits labels as if by the Starlark `str` function applied to a `Label` instance. This is useful for tools that need to match the output of different query commands and/or labels emitted by rules. If not enabled, output formatters are free to emit apparent repository names (relative to the main repository) instead to make the output more readable.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
aquery, cquery: whether to include aspect-generated actions in the output. query: no-op (aspects are always followed).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, then the graph will be emitted 'factored', i.e. topologically-equivalent nodes will be merged together and their labels concatenated. This option is only applicable to --output=graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The maximum length of the label string for a graph node in the output. Longer labels will be truncated; -1 means no truncation. This option is only applicable to --output=graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, implicit dependencies will be included in the dependency graph over which the query operates. An implicit dependency is one that is not explicitly specified in the BUILD file but added by bazel. For cquery, this option controls filtering resolved toolchains.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Includes names of the action inputs and outputs in the output (potentially large).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
aquery, cquery: whether to include aspect-generated actions in the output. query: no-op (aspects are always followed).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Includes the content of the action command lines in the output (potentially large).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Include the file contents for the FileWrite, SourceSymlinkManifest, and RepoMappingManifest actions (potentially large).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Include the content of the param files used in the command (potentially large). Note: Enabling this flag will automatically enable the --include\_commandline flag.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Includes action inputs that were pruned during action execution. Only affects actions that discover inputs and have been executed in a previous invocation. Only takes effect if --include\_artifacts is also set.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, `blaze query --output=build` will output `package_group` targets.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, when outputting package\_group's `packages` attribute, the leading `//` will not be omitted.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set and --universe\_scope is unset, then a value of --universe\_scope will be inferred as the list of unique target patterns in the query expression. Note that the --universe\_scope value inferred for a query expression that uses universe-scoped functions (e.g.`allrdeps`) may not be what you want, so you should use this option only if you know what you are doing. See [https://bazel.build/reference/query#sky-query](https://bazel.build/reference/query#sky-query) for details and examples. If --universe\_scope is set, then this option's value is ignored. Note: this option applies only to `query` (i.e. not `cquery`).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether each format is terminated with \0 instead of newline.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, deps from "nodep" attributes will be included in the dependency graph over which the query operates. A common example of a "nodep" attribute is "visibility". Run and parse the output of `info build-language` to learn about all the "nodep" attributes in the build language.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Whether each format is terminated with \0 instead of newline.
Expands to:
* `--line_terminator_null=true`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The format in which the aquery results should be printed. Allowed values for aquery are: text, textproto, proto, streamed\_proto, jsonproto.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
When specified, query results will be written directly to this file, and nothing will be printed to Bazel's standard output stream (stdout). In benchmarks, this is generally faster than `bazel query > file`.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, attributes whose value is not explicitly specified in the BUILD file are included; otherwise they are omitted. This option is applicable to --output=proto
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the definition\_stack proto field, which records for each rule instance the Starlark call stack at the moment the rule's class was defined.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, configurable attributes created by select() are flattened. For list types the flattened representation is a list containing each value of the select map exactly once. Scalar types are flattened to null.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Populate the source\_aspect\_name proto field of each Attribute with the source aspect that the attribute came from (empty string if it did not).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Use the starlark environment in the value of the generated \$internal\_attr\_hash attribute. This ensures that the starlark rule definition (and its transitive imports) are part of this identifier.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether or not to calculate and populate the \$internal\_attr\_hash attribute.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the instantiation call stack of each rule. Note that this requires the stack to be present
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether to output location information in proto output at all.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Comma separated list of attributes to include in output. Defaults to all attributes. Set to empty string to not output any attribute. This option is applicable to --output=proto.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the rule\_class\_key field of each rule; and for the first rule with a given rule\_class\_key, also populate its rule\_class\_info proto field. The rule\_class\_key field uniquely identifies a rule class, and the rule\_class\_info field is a Stardoc-format rule class API definition.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether or not to populate the rule\_input and rule\_output fields.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, only emits actions that are reachable from the requested top-level targets' default outputs (or specified --output\_groups) in the action graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If set, query will read the query from the file named here, rather than on the command line. It is an error to specify a file here as well as a command-line query.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
If true, the location of BUILD files in xml and proto outputs will be relative. By default, the location output is an absolute path and will not be consistent across machines. You can set this option to true to have a consistent result across machines.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Without performing extra analysis, dump the current Action Graph from Skyframe. Note: Specifying a target with --skyframe\_state is currently not supported. This flag is only available with --output=proto or --output=textproto.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Query: If disabled, dependencies on 'exec configuration' will not be included in the dependency graph over which the query operates. An 'exec configuration' dependency edge, such as the one from any 'proto\_library' rule to the Protocol Compiler, usually points to a tool executed during the build rather than a part of the same 'target' program.
Cquery: If disabled, filters out all configured targets which cross an execution transition from the top-level target that discovered this configured target. That means if the top-level target is in the target configuration, only configured targets also in the target configuration will be returned. If the top-level target is in the exec configuration, only exec configured targets will be returned. This option will NOT exclude resolved toolchains.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
A comma-separated set of target patterns (additive and subtractive). The query may be performed in the universe defined by the transitive closure of the specified targets. This option is used for the query and cquery commands.
For cquery, the input to this option is the targets all answers are built under and so this option may affect configurations and transitions. If this option is not specified, the top-level targets are assumed to be the targets parsed from the query expression. Note: For cquery, not specifying this option may cause the build to break if targets parsed from the query expression are not buildable with top-level options.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that control build execution
Whether to make source manifest actions remotable
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel will run coverage postprocessing for test in a new spawn.
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Add or remove keys from an action's execution info based on action mnemonic.
Applies only to actions which support execution info. Many common actions
support execution info, e.g. Genrule, CppCompile, Javac, StarlarkAction,
TestRunner. When specifying multiple values, order matters because
many regexes may apply to the same mnemonic.
Syntax: `regex=[+-]key,regex=[+-]key,...`.
Examples:
* `.*=+x,.*=-y,.*=+z` adds `x` and `z` to, and removes `y` from, the execution info for all actions.
* `Genrule=+requires-x` adds `requires-x` to the execution info for all Genrule actions.
* `(?!Genrule).*=-requires-x` removes `requires-x` from the execution info for all non-Genrule actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that configure the toolchain used for action execution
Sets the platforms that android\_binary targets use. If multiple platforms are specified, then the binary is a fat APKs, which contains native binaries for each specified target platform.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Specifies a suffix to be added to the configuration directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The C++ compiler to use for compiling the target.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION)
Location of the binary that is used to postprocess raw coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:lcov_merger`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of the binary that is used to generate coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:coverage_report_generator`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of support files that are required on the inputs of every test action
that collects code coverage. Defaults to `//tools/test:coverage_support`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies a custom malloc implementation. This setting overrides malloc attributes in build rules.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, add a "requires-xcode:\{version}" execution requirement to every Xcode action. If the Xcode version has a hyphenated label, also add a "requires-xcode-label:\{version\_label}" execution requirement.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use the most recent Xcode that is available both locally and remotely. If false, or if there are no mutual available versions, use the local Xcode version selected via xcode-select.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
The platforms that are available as execution platforms to run actions.
Platforms can be specified by exact target, or as a target pattern.
These platforms will be considered before those declared in the `WORKSPACE` file by
`register_execution_platforms()`. This option may only be set once; later
instances will override earlier flag settings.
Tags: [`execution`](#effect_tag_EXECUTION)
The toolchain rules to be considered during toolchain resolution.
Toolchains can be specified by exact target, or as a target pattern.
These toolchains will be considered before those declared in the `WORKSPACE` file
by `register_toolchains()`.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
A label to a checked-in libc library. The default value is selected by the crosstool toolchain, and you almost never need to override it.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If specified, this setting overrides the libc top-level directory (--grte\_top) for the exec configuration.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The label of a platform rule that describes the host system.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If enabled, `bazel test --run_under=//:runner` builds `//:runner` in the exec
configuration. If disabled, it builds `//:runner` in the target configuration.
Bazel executes tests on exec machines, so the former is more correct. This
doesn't affect `bazel run`, which always builds `--run_under=//foo` in the
target configuration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Whether to emit a strip action as part of objc linking.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not enable 'host' and 'nonhost' features in the c++ toolchain (see [https://github.com/bazelbuild/bazel/issues/7407](https://github.com/bazelbuild/bazel/issues/7407) for more information).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not link library dependencies as whole archive by default (see [https://github.com/bazelbuild/bazel/issues/7362](https://github.com/bazelbuild/bazel/issues/7362) for migration instructions).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, strip action for executables will use flag -x, which does not break dynamic symbol resolution.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Use interface shared objects if supported by the toolchain. All ELF toolchains currently support this setting.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The minimum OS version which your compilation targets.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The location of a mapping file that describes which platform to use if none is set or
which flags to set when a platform already exists. Must be relative to the main
workspace root. Defaults to `platform_mappings` (a file directly under the
workspace root).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
The labels of the platform rules describing the target platforms for the current command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, uses Xcode of the given version for relevant build actions. If unspecified, uses the executor default version of Xcode.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
The label of the xcode\_config rule to be used for selecting the Xcode version in the build configuration.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that control the output of the command
Whether to generate debug symbol(.dSYM) file(s).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, build runfiles symlink forests for all targets. If false, write them only when required by a local action, test or run command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, write runfiles manifests for all targets. If false, omit them. Local tests will fail to run when false.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, when building C++ tests statically and with fission the .dwp file for the test binary will be automatically built as well.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the suffixes of header files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Sets the suffixes of source files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Pass the --include\_source\_info flag when building a proto\_library. This results in vastly larger descriptors that include information about the original location of each decl in the source file as well as surrounding comments.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Save the state of enabled and requested feautres as an output of compilation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Specifies which compilation modes use fission for C++ compilations and links. May be any combination of \{'fastbuild', 'dbg', 'opt'} or the special values 'yes' to enable all modes and 'no' to disable all modes.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, native rules add `DefaultInfo.files` of data dependencies to their runfiles,
which matches the recommended behavior for Starlark rules ([runfiles features to avoid](https://bazel.build/extending/rules#runfiles_features_to_avoid)).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, the `{binary}.repo_mapping` file emits a module extension's repo mapping
only once instead of once for each repo generated by the extension that
contributes runfiles.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
List of flags for which the use in `select()` is disabled.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If true, runfiles of targets listed in the srcs attribute are available to targets that consume the filegroup as a data dependency.
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, when artifacts from the same target in multiple configurations are encountered
when constructing runfiles, prefer the version that matches the configuration of the
depending target. Specifically, when a target T depends on a target A in multiple
configurations, either directly or transitively, prefer the runfiles from the
version of A in the configuration that matches the configuration of T. This can happen,
for example, when a target appears in both the tools and data attributes.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Specifies whether to generate a linkmap file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, temporary outputs from gcc will be saved. These include .s files (assembler code), .i files (preprocessed C) and .ii files (preprocessed C++).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Specifies the set of environment variables available to actions with target
configuration. Variables can be either specified by `name`, in which case
the value will be taken from the invocation environment, by the `name=value`
pair which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can be used
multiple times; for options given for the same variable, the latest wins,
options for different variables accumulate.
Note that unless `--incompatible_repo_env_ignores_action_env` is true, all `name=value`
pairs will be available to repository rules.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Allowed values for the `--cpu` flag.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the order of manifests passed to the manifest merger for Android binaries. ALPHABETICAL means manifests are sorted by path relative to the execroot. ALPHABETICAL\_BY\_CONFIGURATION means manifests are sorted by paths relative to the configuration directory within the output directory. DEPENDENCY means manifests are ordered with each library's manifest coming before the manifests of its dependencies.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`execution`](#effect_tag_EXECUTION)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, Bazel will instrument code (using offline instrumentation where
possible) and will collect coverage information during tests. Only targets that
match `--instrumentation_filter` will be affected. Usually this option should
not be specified directly - `bazel coverage` command should be used instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-c`
Specify the mode the binary will be built in. Values: `fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to gcc when compiling C source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to gcc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Deprecated: this flag is not used internally by Blaze although there are legacy platform
mappings to allow for backwards compatibility. Do not use this flag, instead use
`--platforms` with an appropriate platform definition.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use CSFDO profile information to optimize compilation. Specify the absolute path name of the zip file containing the profile file, a raw or an indexed LLVM profile file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Generate binaries with context sensitive FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The cs\_fdo\_profile representing the context sensitive profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to gcc when compiling C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each `--define` option specifies an assignment for a build variable.
In case of multiple values for a variable, the last one wins.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Determines whether C++ binaries will be linked dynamically. 'default' means Bazel will choose whether to link dynamically. 'fully' means all libraries will be linked dynamically. 'off' means that all libraries will be linked in mostly static mode, the exception being dynamically linked system libraries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for propeller optimize will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for FDO will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Enable runfiles symlink tree; By default, it's off on Windows, on on other platforms.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of aspects to be applied to exec-configured targets, regardless of whether or not they are top-level targets. This is an experimental feature and is subject to change.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Use `action_listener` to attach an `extra_action` to
existing build actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Compress Java resources in APKs
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If specified, Bazel will also generate collect coverage information for generated files.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use libunwind for stack unwinding, and compile with -fomit-frame-pointer and -fasynchronous-unwind-tables.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Which model to use for where in the output tree rules write their outputs, particularly
for multi-platform / multi-configuration builds. This is highly experimental. See
[GH-6526](https://github.com/bazelbuild/bazel/issues/6526) for details. Starlark actions can opt into path mapping by adding the key
`supports-path-mapping` to the `execution_requirements` dict.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
If specified, Bazel will generate llvm-cov coverage map information rather than gcov when collect\_code\_coverage is enabled.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Please only use this flag as part of a suggested migration or testing strategy. Note
that the heuristic has known deficiencies and it is suggested to migrate to
relying on just `--override_platform_cpu_name`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Generate binaries with FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use FDO profile information to optimize compilation. Specify the name of a zip file containing a .gcda file tree, an afdo file containing an auto profile, or an LLVM profile file. This flag also accepts files specified as labels (e.g. `//foo/bar:file.afdo` - you may need to add an `exports_files` directive to the corresponding package) and labels pointing to `fdo_profile` targets. This flag will be superseded by the `fdo_profile` rule.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use cache prefetch hints.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The fdo\_profile representing the profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the target configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
See also `--host_features`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, all C++ compilations produce position-independent code ("-fPIC"), links prefer PIC pre-built libraries over non-PIC libraries, and links produce position-independent executables ("-pie").
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to actions with execution
configurations. Variables can be either specified by `name`, in which case the
value will be taken from the invocation environment, by the `name=value` pair
which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can
be used multiple times; for options given for the same variable, the latest
wins, options for different variables accumulate.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Specify the mode the tools used during the build will be built in. Values:
`fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to the C compiler when compiling C (but not C++) source files in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to the C compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The host CPU.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to C++ compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the exec configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to linker when linking tools in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible macOS version for host targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Additional options to selectively pass to the C/C++ compiler when compiling certain files in the exec configurations. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --host\_per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When enabled, an exec groups is automatically created for each toolchain used by a rule.
For this to work rule needs to specify `toolchain` parameter on its actions. For
more information, see [GH-17134](https://github.com/bazelbuild/bazel/issues/17134).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, the genfiles directory is folded into the bin directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If specified, the value of the cpu constraint (`@platforms//cpu:cpu`) of
the target platform is used to set the `$(TARGET_CPU)` make variable.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When coverage is enabled, specifies whether to consider instrumenting test rules.
When set, test rules included by `--instrumentation_filter` are instrumented.
Otherwise, test rules are always excluded from coverage instrumentation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When coverage is enabled, only rules with names included by the
specified regex-based filter will be instrumented. Rules prefixed
with '-' are excluded instead. Note that only non-test rules are
instrumented unless `--instrument_test_targets` is enabled.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible iOS version for target simulators and devices. If unspecified, uses 'ios\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures to build an ios\_application with. The result is a universal binary containing all specified architectures.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional option to pass to gcc when linking.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO backend step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO indexing step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple macOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible macOS version for targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use memprof profile.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether to perform symbol and dead-code strippings on linked binaries. Binary strippings will be performed if both this flag and --compilation\_mode=opt are specified.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional options to pass to gcc when compiling Objective-C/C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Each entry should be of the form `label=value` where label refers to a platform and values
is the desired shortname to override the platform's CPU name in `$(TARGET_CPU)`
make variable and output path. Only used when `--incompatible_target_cpu_from_platform` or
`--incompatible_bep_cpu_from_platform` is true. Has highest naming priority.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to gcc when compiling certain files. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to LTO backend (under --features=thin\_lto) when compiling certain backend objects. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns. option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_ltobackendopt=//foo/.\*.o,-//foo/bar.o\@-O0 adds the -O0 command line option to the LTO backend command line of all o files in //foo/ except bar.o.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a suffix to be added to the configuration directory.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Use Propeller profile information to optimize the build target.A propeller profile must consist of at least one of two files, a cc profile and a ld profile. This flag accepts a build label which must refer to the propeller profile input files. For example, the BUILD file that defines the label, in a/b/BUILD:propeller\_optimize( name = "propeller\_profile", cc\_profile = "propeller\_cc\_profile.txt", ld\_profile = "propeller\_ld\_profile.txt",)An exports\_files directive may have to be added to the corresponding package to make these files visible to Bazel. The option must be used as: --propeller\_optimize=//a/b:propeller\_profile
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of cc\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of ld\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Prefix to insert before the executables for the `test` and `run` commands.
If the value is `foo -bar`, and the execution command line is `test_binary -baz`,
then the final command line is `foo -bar test_binary -baz`.
This can also be a label to an executable target. Some examples are:
* `valgrind`
* `strace`
* `strace -c`
* `valgrind --quiet --num-callers=20`
* `//package:target`
* `//package:target --options`
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, native libraries that contain identical functionality will be shared among different targets
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Stamp binaries with the date, username, hostname, workspace information, etc.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether to strip binaries and shared libraries (using "-Wl,--strip-debug"). The default value of 'sometimes' means strip iff --compilation\_mode=fastbuild.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to strip when generating a '\.stripped' binary.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple tvOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible tvOS version for target simulators and devices. If unspecified, uses 'tvos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures for which to build Apple visionOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Comma-separated list of architectures for which to build Apple watchOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible watchOS version for target simulators and devices. If unspecified, uses 'watchos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use XbinaryFDO profile information to optimize compilation. Specify the name of default cross binary profile. When the option is used together with --fdo\_instrument/--fdo\_optimize/--fdo\_profile, those options will always prevail as if xbinary\_fdo is never specified.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If disabled, visibility errors in target dependencies are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Whether to desugar Java 8 bytecode before dexing.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Whether to include supported Java 8 libraries in apps for legacy devices.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Checks the environments each target is compatible with and reports errors if any target has dependencies that don't support the same environments
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable package()s to set the transitive\_visibility attribute to restrict which packages may depend on them.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, enforce that a java\_binary rule can't contain more than one version of the same class file on the classpath. This enforcement can break the build, or can just result in warnings.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If true, checks that a Java target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If enabled, check testonly for prerequisite targets that are output files by looking up the testonly of the generating rule. This matches visibility checking.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When enabled, and with experimental\_one\_version\_enforcement set to a non-NONE value, enforce one version on java\_test targets. This flag can be disabled to improve incremental test performance at the expense of missing potential one version violations.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Unless OFF, checks that a proto\_library target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Unless OFF, checks that a proto\_library target explicitly declares all targets used in 'import public' as exported.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, headers found through system include paths (-isystem) are also required to be declared.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Declares this build's target environment. Must be a label reference to an
`environment` rule. If specified, all top-level targets must be compatible with this
environment.
See also `--platforms`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Options that affect the signing outputs of a build
Implementation to use to sign APKs
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set, and compilation mode is not 'opt', objc apps will include debug entitlements when signing.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If true, disallow sdk\_frameworks and weak\_sdk\_frameworks attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, make the default value true for alwayslink attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
If true, an analysis failure of a rule target results in the target's propagation
of an instance of `AnalysisFailureInfo` containing the error description, instead
of resulting in a build failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Sets the maximum number of transitive dependencies through a rule attribute with
a `for_analysis_testing` configuration transition.
Exceeding this limit will result in a rule error.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Override the default resources amount for tests. The expected format is
`{resource}={value}`. If a single positive number is specified as `{value}`
it will override the default resources for all test sizes. If 4
comma-separated numbers are specified, they will override the resource
amount for respectively the `small`, `medium`, `large`, `enormous` test sizes.
Values can also be `HOST_RAM`/`HOST_CPU`, optionally followed
by `[-|*]{float}` (eg. `memory=HOST_RAM*.1,HOST_RAM*.2,HOST_RAM*.3,HOST_RAM*.4`).
The default test resources specified by this flag are overridden by explicit
resources specified in tags.
*May be used multiple times; values are accumulated.*
Specifies number of times to run each test. If any of those attempts fail for any
reason, the whole test is considered failed. Normally the value specified is
just an integer.
Example: `--runs_per_test=3` will run all tests 3 times.
Alternate syntax: `regex_filter@runs_per_test`. Where `runs_per_test` stands for
an integer value and `regex_filter` stands for a list of include and exclude
regular expression patterns (Also see --instrumentation\_filter).
Example: `--runs_per_test=//foo/.*,-//foo/bar/.*@3` runs all tests in `//foo/` except
those under `//foo/bar` three times. This option can be passed multiple times. The most
recently passed argument that matches takes precedence. If nothing matches,
the test is only run once.
*May be used multiple times; values are accumulated.*
Specifies additional environment variables to be injected into the test runner
environment. Variables can be either specified by `name`, in which
case its value will be read from the Bazel client environment, or by the
`name=value` pair.
Previously set variables can be unset via `=name`.
This option can be used multiple times to specify several variables.
Used only by the 'bazel test' command.
*May be used multiple times; values are accumulated.*
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Override the default test timeout values for test timeouts (in secs). If a single
positive integer value is specified it will override all categories. If 4
comma-separated integers are specified, they will override the timeouts for
`short`, `moderate`, `long` and `eternal` (in that order). In either form, a value of
-1 tells blaze to use its default timeouts for that category.
If true, undeclared test outputs will be archived in a zip file.
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Options that trigger optimizations of the build time
Whether to generate and analyze .d files.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, C++ .d files will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, the dependency (.jdeps) files generated from Java compilations will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, `--trim_test_configuration` will not trim the test configuration for rules
marked testonly=1. This is meant to reduce action conflict issues when non-test
rules depend on `cc_test` rules. No effect if `--trim_test_configuration` is
false.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set, .d files emitted by clang will be used to prune the set of inputs passed into objc compiles.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
When building a target //a:a, process headers in all targets that //a:a depends on (if header processing is enabled for the toolchain).
Tags: [`execution`](#effect_tag_EXECUTION)
When enabled, test-related options will be cleared below the top level of the build. When this flag is active, tests cannot be built as dependencies of non-test rules, but changes to test-related options will not cause non-test rules to be re-analyzed.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Options that affect the verbosity, format or location of logging
Print debug information during toolchain resolution. The flag takes a regex, which is checked against toolchain types and specific targets to see which to debug. Multiple regexes may be separated by commas, and then each regex is checked separately. Note: The output of this flag is very complex and will likely only be useful to experts in toolchain resolution.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, visibility errors include additional diagnostic information.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Sets a shorthand name for a Starlark flag. It takes a single key-value pair in the form
`{key}={value}` as an argument.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Miscellaneous options, not otherwise categorized.
Short form: `-t`
If set to `auto`, Bazel reruns a test if and only if:
* Bazel detects changes in the test or its dependencies,
* The test is marked as `external`,
* Multiple test runs were requested with `--runs_per_test`, or
* The test previously failed.
If set to `yes`, Bazel caches all test results except for tests marked as
`external`. If set to `no`, Bazel does not cache any test results.
If `on_failed` or `on_passed`, then Blaze will cancel concurrently running tests on the first
successful run with that result. This is only useful in combination with
`--runs_per_test_detects_flakes`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel fetches the entire coverage data directory for each test during a coverage run.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, coverage for clang will generate an LCOV report.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables reduced classpaths for Java compilations.
Whether to validate java\_\* sources.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The number of CPUs to reserve for Turbine.
Explicitly specify a dependency to JUnit or Hamcrest in a java\_test instead of accidentally obtaining from the TestRunner's deps. Only works for bazel right now.
The Java launcher used by tools that are executed during a build.
Additional options to pass to javac when building tools that are executed during a build.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM when building tools that are executed during the build. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
If true, exclusive tests will run with sandboxed strategy. Add `local` tag to force
an exclusive test run locally
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel uses an environment with a static value for PATH and does not
inherit `LD_LIBRARY_PATH`. Use `--action_env=ENV_VARIABLE` if you want to
inherit specific environment variables from the client, but note that doing so
can prevent cross-user caching if a shared cache is used.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Causes the Java virtual machine of a java test to wait for a connection from a JDWP-compliant debugger (such as jdb) before starting the test. Implies -test\_output=streamed.
Expands to:
* `--test_arg=--wrapper_script_flag=--debug`
* `--test_output=streamed`
* `--test_strategy=exclusive`
* `--test_timeout=9999`
* `--nocache_test_results`
Generate dependency information (for now, compile-time classpath) per Java target.
Compile ijars directly from source.
The Java language version
The Java launcher to use when building Java binaries. If this flag is set to the empty string, the JDK launcher is used. The "launcher" attribute overrides this flag.
The Java runtime version
Additional options to pass to javac.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
Specifies a binary to use to generate the list of classes that must be in the main dex when compiling legacy multidex.
Specifies a binary to use to do dexing without sharding.
Plugins to use in the build. Currently works with java\_plugin.
*May be used multiple times; values are accumulated.*
Specifies which version of ProGuard to use for code removal when building a Java binary.
The label of the proto-compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether to pass profile\_path to the proto compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
The profile to pass to the proto compiler as profile\_path. If unset, but --proto\_profile is true (the default), infers the path from --fdo\_optimize.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile C++ protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile Java protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile JavaLite protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional options to pass to the protobuf compiler.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, any shard in which at least one run/attempt passes and at least one run/attempt fails gets a FLAKY status.
Absolute path to the shell executable for Bazel to use. If this is unset, but the
`BAZEL_SH` environment variable is set on the first Bazel invocation (that starts
up a Bazel server), Bazel uses that. If neither is set, Bazel uses a hard-coded
default path depending on the operating system it runs on;
* Windows: `c:/msys64/usr/bin/bash.exe`
* FreeBSD and OpenBSD: `/usr/local/bin/bash`
* All others: `/bin/bash`.
Note that using a shell that is not compatible with `bash` may lead
to build failures or runtime failures of the generated binaries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies additional options and arguments that should be passed to the test
executable. Can be used multiple times to specify several arguments.
If multiple tests are executed, each of them will receive identical arguments.
Used only by the `bazel test` command.
*May be used multiple times; values are accumulated.*
Specifies a filter to forward to the test framework. Used to limit the tests run. Note that this does not affect which targets are built.
Forwards fail fast option to the test runner. The test runner should stop execution upon first failure.
Specify strategy for test sharding:
* `explicit` to only use sharding if the `shard_count` `BUILD` attribute is
present.
* `disabled` to never use test sharding.
* `forced=k` to enforce `k` shards for testing regardless of the `shard_count` `BUILD`
attribute.
The Java language version used to execute the tools that are needed during a build
The Java runtime version used to execute tools during the build
If enabled, this option causes Java compilation to use interface jars. This will result in faster incremental compilation, but error messages can be different.
## Build Options
Options that control build execution
If set, allow at least one action to run even if the resource is not enough or unavailable.
Tags: [`execution`](#effect_tag_EXECUTION)
Filters spawn strategies by the execution platform without affecting order.
For example:
```
common --spawn_strategy=remote,sandboxed,worker,local
common --strategy=Genrule=local
common --allowed_strategies_by_exec_platform=@platforms//host:host=local,sandboxed,worker
common --allowed_strategies_by_exec_platform=//:linux_amd64=remote
```
With the above options;
* Actions configured for the host platform will be given `remote,sandboxed,worker`.
* Actions configured for the `//:linux_amd64` platform will be given `remote`.
* Actions configured for the `//:linux_amd64` platform with mnemonic `Genrule` will be
given no strategies and fail to spawn.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
Don't perform the build, just check if it is up-to-date. If all targets are up-to-date, the build completes successfully. If any step needs to be executed an error is reported and the build fails.
Tags: [`execution`](#effect_tag_EXECUTION)
How many milliseconds should local execution be delayed, if remote execution was faster during a build at least once?
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The local strategies, in order, to use for the given mnemonic - the first applicable strategy is used. For example, `worker,sandboxed` runs actions that support persistent workers using the worker strategy, and all others using the sandboxed strategy. If no mnemonic is given, the list of strategies is used as the fallback for all mnemonics. The default fallback list is `worker,sandboxed`, or`worker,sandboxed,standalone` if `experimental_local_lockfree_output` is set. Takes \[mnemonic=]local\_strategy\[,local\_strategy,...]
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The remote strategies, in order, to use for the given mnemonic - the first applicable strategy is used. If no mnemonic is given, the list of strategies is used as the fallback for all mnemonics. The default fallback list is `remote`, so this flag usually does not need to be set explicitly. Takes \[mnemonic=]remote\_strategy\[,remote\_strategy,...]
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If set to true, Bazel is allowed to run action in a virtual thread. The number of
actions in flight is still capped with `--jobs`.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
The number of maximum concurrent actions to run with async execution. If the value is
less than `--jobs`, it is clamped to `--jobs`.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
Specify a Docker image name (e.g. "ubuntu:latest") that should be used to execute a sandboxed action when using the docker strategy and the action itself doesn't already have a container-image attribute in its exec\_properties in the platform description. The value of this flag is passed verbatim to 'docker run', so it supports the same syntax and mechanisms as Docker itself.
Tags: [`execution`](#effect_tag_EXECUTION)
If enabled, injects the uid and gid of the current user into the Docker image before using it. This is required if your build / tests depend on the user having a name and home directory inside the container. This is on by default, but you can disable it in case the automatic image customization feature doesn't work in your case or you know that you don't need it.
Tags: [`execution`](#effect_tag_EXECUTION)
If true, cancels the remote branch when the local branch finishes first in dynamic execution. If false, allows the remote branch to continue running to completion in the background to populate the remote action cache for future builds.
Tags: [`execution`](#effect_tag_EXECUTION)
When set, targets that are build "for tool" are not subject to dynamic execution. Such targets are extremely unlikely to be built incrementally and thus not worth spending local cycles on.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Controls how much load from dynamic execution to put on the local machine. This flag adjusts how many actions in dynamic execution we will schedule concurrently. It is based on the number of CPUs Blaze thinks is available, which can be controlled with the --local\_resources=cpu= flag.
If this flag is 0, all actions are scheduled locally immediately. If > 0, the amount of actions scheduled locally is limited by the number of CPUs available. If \< 1, the load factor is used to reduce the number of locally scheduled actions when the number of actions waiting to schedule is high. This lessens the load on the local machine in the clean build case, where the local machine does not contribute much.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If >0, the time a dynamically run action must run remote-only before we prioritize its local execution to avoid remote timeouts. This may hide some problems on the remote execution system. Do not turn this on without monitoring of remote execution issues.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Enable Docker-based sandboxing. This option has no effect if Docker is not installed.
Tags: [`execution`](#effect_tag_EXECUTION)
If set to true, the contents of stashed sandboxes for reuse\_sandbox\_directories will be tracked in memory. This reduces the amount of I/O needed during reuse. Depending on the build this flag may improve wall time. Depending on the build as well this flag may use a significant amount of additional memory.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
If 0, sandboxes are deleted as soon as actions finish, blocking action completion. If greater than 0, sandboxes are deleted asynchronously in the background without blocking action completion. Asynchronous deletion uses a single thread while a command is running, but ramps up to as many threads as the value of this flag once the server becomes idle. Set to `auto` to use as many threads as the number of CPUs. A server shutdown blocks on any pending asynchronous deletions.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
If true, actions whose mnemonic matches the input regex will have their resources request enforced as limits, overriding the value of --experimental\_sandbox\_limits, if the resource type supports it. For example a test that declares cpu:3 and resources:memory:10, will run with at most 3 cpus and 10 megabytes of memory.
Tags: [`execution`](#effect_tag_EXECUTION)
If > 0, each Linux sandbox will be limited to the given amount for the specified resource. This overrides --experimental\_sandbox\_memory\_limit\_mb. Requires cgroups v1 or v2 and permissions for the users to the cgroups dir.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
If > 0, each Linux sandbox will be limited to the given amount of memory (in MB). Requires cgroups v1 or v2 and permissions for the users to the cgroups dir.
Tags: [`execution`](#effect_tag_EXECUTION)
If enabled, could shrink worker pool if worker memory pressure is high. This flag works only when flag experimental\_total\_worker\_memory\_limit\_mb is enabled.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If this limit is greater than zero idle workers might be killed if the total memory usage of all workers exceed the limit.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If set to true, do not mount root, only mount whats provided with sandbox\_add\_mount\_pair. Input files will be hardlinked to the sandbox instead of symlinked to from the sandbox. If action input files are located on a filesystem different from the sandbox, then the input files will be copied instead.
Tags: [`execution`](#effect_tag_EXECUTION)
Use Windows sandbox to run actions. If "yes", the binary provided by --experimental\_windows\_sandbox\_path must be valid and correspond to a supported version of sandboxfs. If "auto", the binary may be missing or not compatible.
Tags: [`execution`](#effect_tag_EXECUTION)
Path to the Windows sandbox binary to use when --experimental\_use\_windows\_sandbox is true. If a bare name, use the first binary of that name found in the PATH.
Tags: [`execution`](#effect_tag_EXECUTION)
If non-empty, only allow using persistent workers with the given worker key mnemonic.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If enabled, Bazel may send cancellation requests to workers that support them.
Tags: [`execution`](#effect_tag_EXECUTION)
If this limit is greater than zero, workers might be killed if the memory usage of the worker exceeds the limit. If not used together with dynamic execution and `--experimental_dynamic_ignore_local_signals=9`, this may crash your build.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
The interval between collecting worker metrics and possibly attempting evictions. Cannot effectively be less than 1s for performance reasons.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If enabled, multiplex workers with a 'supports-multiplex-sandboxing' execution requirement will run in a sandboxed environment, using a separate sandbox directory per work request. Multiplex workers with the execution requirement are always sandboxed when running under the dynamic execution strategy, irrespective of this flag.
Tags: [`execution`](#effect_tag_EXECUTION)
If enabled, workers are run in a hardened sandbox, if the implementation allows it. If hardening is enabled then tmp directories are distinct for different workers.
Tags: [`execution`](#effect_tag_EXECUTION)
A worker key mnemonic for which the contents of the sandbox directory are tracked in memory. This may improve build performance at the cost of additional memory usage. Only affects sandboxed workers. May be specified multiple times for different mnemonics.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
If enabled, actions arguments for workers that do not follow the worker specification will cause an error. Worker arguments must have exactly one @flagfile argument as the last of its list of arguments.
Tags: [`execution`](#effect_tag_EXECUTION)
Specify how to execute genrules. This flag will be phased out. Instead, use --spawn\_strategy=\ to control all actions or --strategy=Genrule=\ to control genrules only.
Tags: [`execution`](#effect_tag_EXECUTION)
Placeholder option so that we can tell in Blaze whether the spawn scheduler was enabled.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Short form: `-j`
The number of concurrent jobs to run. Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". Values must be between 1 and 5000. Values above 2500 may cause memory issues. "auto" calculates a reasonable default based on host resources.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
Short form: `-k`
Continue as much as possible after an error. While the target that failed and those that depend on it cannot be analyzed, other prerequisites of these targets can be.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Number of parallel threads to use for the loading/analysis phase.Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". "auto" sets a reasonable default based on host resources. Must be at least 1.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
If set to true, directories used by sandboxed non-worker execution may be reused to avoid unnecessary setup costs.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
Lets the sandbox create its sandbox directories underneath this path. Specify a path on tmpfs (like /run/shm) to possibly improve performance a lot when your build / tests have many input files. Note: You need enough RAM and free space on the tmpfs to hold output and intermediate files generated by running actions.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
If true, a loopback device will be set up in the linux-sandbox network namespace for local actions.
Tags: [`execution`](#effect_tag_EXECUTION)
Explicitly enable the creation of pseudoterminals for sandboxed actions. Some linux distributions require setting the group id of the process to 'tty' inside the sandbox in order for pseudoterminals to function. If this is causing issues, this flag can be disabled to enable other groups to be used.
Tags: [`execution`](#effect_tag_EXECUTION)
For sandboxed actions, mount an empty, writable directory at this absolute path (if supported by the sandboxing implementation, ignored otherwise).
*May be used multiple times; values are accumulated.*
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
Skip incompatible targets that are explicitly listed on the command line.
By default, building such targets results in an error but they are
silently skipped when this option is enabled. See: [Skipping incompatible targets](https://bazel.build/extending/platforms#skipping-incompatible-targets)
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specify how spawn actions are executed by default. Accepts a comma-separated list of strategies from highest to lowest priority. For each action Bazel picks the strategy with the highest priority that can execute the action. The default value is "remote,worker,sandboxed,local". See [https://blog.bazel.build/2019/06/19/list-strategy.html](https://blog.bazel.build/2019/06/19/list-strategy.html) for details.
Tags: [`execution`](#effect_tag_EXECUTION)
Specify how to distribute compilation of other spawn actions. Accepts a comma-separated list of strategies from highest to lowest priority. For each action Bazel picks the strategy with the highest priority that can execute the action. The default value is "remote,worker,sandboxed,local". This flag overrides the values set by --spawn\_strategy (and --genrule\_strategy if used with mnemonic Genrule). See [https://blog.bazel.build/2019/06/19/list-strategy.html](https://blog.bazel.build/2019/06/19/list-strategy.html) for details.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
Override which spawn strategy should be used to execute spawn actions that have descriptions matching a certain regex\_filter. See --per\_file\_copt for details on regex\_filter matching. The last regex\_filter that matches the description is used. This option overrides other flags for specifying strategy. Example: --strategy\_regexp=//foo.*.cc,-//foo/bar=local means to run actions using local strategy if their descriptions match //foo.*.cc but not //foo/bar. Example: --strategy\_regexp='Compiling.\*/bar=local --strategy\_regexp=Compiling=sandboxed will run 'Compiling //foo/bar/baz' with the 'local' strategy, but reversing the order would run it with 'sandboxed'.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
Extra command-flags that will be passed to worker processes in addition to --persistent\_worker, keyed by mnemonic (e.g. --worker\_extra\_flag=Javac=--debug.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
How many instances of each kind of persistent worker may be launched if you use the 'worker' strategy. May be specified as \[name=value] to give a different value per mnemonic. The limit is based on worker keys, which are differentiated based on mnemonic, but also on startup flags and environment, so there can in some cases be more workers per mnemonic than this flag specifies. Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". 'auto' calculates a reasonable default based on machine capacity. "=value" sets a default for unspecified mnemonics.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
How many WorkRequests a multiplex worker process may receive in parallel if you use the 'worker' strategy with --worker\_multiplex. May be specified as \[name=value] to give a different value per mnemonic. The limit is based on worker keys, which are differentiated based on mnemonic, but also on startup flags and environment, so there can in some cases be more workers per mnemonic than this flag specifies. Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". 'auto' calculates a reasonable default based on machine capacity. "=value" sets a default for unspecified mnemonics.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If enabled, workers will use multiplexing if they support it.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If enabled, all workers quit after a build is done.
Tags: [`execution`](#effect_tag_EXECUTION), [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If enabled, singleplex workers will run in a sandboxed environment. This may be set as a plain boolean (the traditional --worker\_sandboxing / --noworker\_sandboxing forms still work), or as \[mnemonic=]value to enable or disable sandboxing per worker-key mnemonic; a value with no mnemonic applies to all mnemonics. Later values override earlier ones for the mnemonics they affect. Singleplex workers are always sandboxed when running under the dynamic execution strategy or with path mapping, irrespective of this flag.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
If enabled, prints verbose messages when workers are started, shutdown, ...
Options that control the output of the command
Execute the build; this is the usual behaviour.
Specifying `--nobuild` causes the build to stop before executing the build
actions, returning zero if the package loading and analysis phases completed
successfully; this mode is useful for testing those phases.
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether to run validation actions using aspect (for parallelism with tests).
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, building explicitly requested output groups that are not present on any top-level target or aspect fails the build.
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
A list of comma-separated output group names, each of which optionally prefixed by a `+`
or a `-`. A group prefixed by `+` is added to the default set of output groups,
while a group prefixed by `-` is removed from the default set. If at least one
group is not prefixed, the default set of output groups is omitted. For example,
`--output_groups=+foo,+bar` builds the union of the default set, foo, and bar,
while `--output_groups=foo,bar` overrides the default set such that only foo and
bar are built.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether to run validation actions as part of the build. See [Validation Actions](https://bazel.build/extending/rules#validation_actions).
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Dump a profile of serialized frontier bytes. Specifies the output path.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Comma-separated list of aspects to be applied to top-level targets. In the list, if
aspect `some_aspect` specifies required aspect providers via
`required_aspect_providers`, `some_aspect` will run after
every aspect that was mentioned before it in the aspects list whose advertised
providers satisfy `some_aspect` required aspect providers. Moreover,
`some_aspect` will run after all its required aspects specified by
`requires` attribute.
`some_aspect` will then have access to the values of those aspects'
providers.
`{bzl-file-label}%{aspect_name}`, for example `//tools:my_def.bzl%my_aspect`, where
`my_aspect` is a top-level value from a file `tools/my_def.bzl`.
*May be used multiple times; values are accumulated.*
Maximum number of open files allowed during BEP artifact upload.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
This flag controls how the convenience symlinks (the symlinks that appear in the
workspace after the build) will be managed. Possible values:
* `normal` (default): Each kind of convenience symlink will be created or deleted,
as determined by the build.
* `clean`: All symlinks will be unconditionally deleted.
* `ignore`: Symlinks will not be created or cleaned up.
* `log_only`: Generate log messages as if `normal` were passed, but don't actually
perform any filesystem operations (useful for tools).
Note that only symlinks whose names are generated by the current value of
`--symlink_prefix` can be affected; if the prefix changes, any pre-existing
symlinks will be left alone.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
This flag controls whether or not we will post the build event
`ConvenienceSymlinksIdentified` to the Build Event Protocol. If the value is true,
the BEP will have an entry for `convenienceSymlinksIdentified`,
listing all of the convenience symlinks created in your workspace. If false, then
the `convenienceSymlinksIdentified` entry in the BEP will be empty.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Downloads all remote outputs to the local machine. This flag is an alias for --remote\_download\_outputs=all.
Expands to:
* `--remote_download_outputs=all`
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Does not download any remote build outputs to the local machine. This flag is an alias for --remote\_download\_outputs=minimal.
Expands to:
* `--remote_download_outputs=minimal`
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set to 'minimal' doesn't download any remote build outputs to the local machine, except the ones required by local actions. If set to 'toplevel' behaves like 'minimal' except that it also downloads outputs of top level targets to the local machine. Both options can significantly reduce build times if network bandwidth is a bottleneck.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Instead of downloading remote build outputs to the local machine, create symbolic links. The target of the symbolic links can be specified in the form of a template string. This template string may contain \{hash} and \{size\_bytes} that expand to the hash of the object and the size in bytes, respectively. These symbolic links may, for example, point to a FUSE file system that loads objects from the CAS on demand.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Only downloads remote outputs of top level targets to the local machine. This flag is an alias for --remote\_download\_outputs=toplevel.
Expands to:
* `--remote_download_outputs=toplevel`
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The prefix that is prepended to any of the convenience symlinks that are created
after a build. If omitted, the default value is the name of the build tool
followed by a hyphen. If `/` is passed, then no symlinks are created and no
warning is emitted. Warning: the special functionality for `/` will be deprecated
soon; use `--experimental_convenience_symlinks=ignore` instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If enabled, Bazel will pass the --privileged flag to 'docker run' when running actions. This might be required by your build, but it might also result in reduced hermeticity.
Tags: [`execution`](#effect_tag_EXECUTION)
No-op
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`execution`](#effect_tag_EXECUTION)
Add additional path pair to mount in sandbox.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
For sandboxed actions, disallow access to this path.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
Allow network access by default for actions; this may not work with all sandboxing implementations.
Tags: [`execution`](#effect_tag_EXECUTION)
Change the current hostname to 'localhost' for sandboxed actions.
Tags: [`execution`](#effect_tag_EXECUTION)
Change the current username to 'nobody' for sandboxed actions.
Tags: [`execution`](#effect_tag_EXECUTION)
For sandboxed actions, make an existing directory writable in the sandbox (if supported by the sandboxing implementation, ignored otherwise).
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If incompatible\_enforce\_config\_setting\_visibility=false, this is a noop. Else, if this flag is false, any config\_setting without an explicit visibility attribute is //visibility:public. If this flag is true, config\_setting follows the same visibility logic as all other rules. See [https://github.com/bazelbuild/bazel/issues/12933](https://github.com/bazelbuild/bazel/issues/12933).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, enforce config\_setting visibility restrictions. If false, every config\_setting is visible to every target. See [https://github.com/bazelbuild/bazel/issues/12932](https://github.com/bazelbuild/bazel/issues/12932).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
Don't run tests, just check if they are up-to-date. If all tests results are up-to-date, the testing completes successfully. If any test needs to be built or executed, an error is reported and the testing fails. This option implies --check\_up\_to\_date behavior.
Tags: [`execution`](#effect_tag_EXECUTION)
Each test will be retried up to the specified number of times in case of any test failure. Tests that required more than one attempt to pass are marked as 'FLAKY' in the test summary. Normally the value specified is just an integer or the string 'default'. If an integer, then all tests will be run up to N times. If 'default', then only a single test attempt will be made for regular tests and three for tests marked explicitly as flaky by their rule (flaky=1 attribute). Alternate syntax: regex\_filter\@flaky\_test\_attempts. Where flaky\_test\_attempts is as above and regex\_filter stands for a list of include and exclude regular expression patterns (Also see --runs\_per\_test). Example: --flaky\_test\_attempts=//foo/.*,-//foo/bar/.*@3 deflakes all tests in //foo/ except those under foo/bar three times. This option can be passed multiple times. The most recently passed argument that matches takes precedence. If nothing matches, behavior is as if 'default' above.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION)
The max number of local test jobs to run concurrently. Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". 0 means local resources will limit the number of local test jobs to run concurrently instead. Setting this greater than the value for --jobs is ineffectual.
Tags: [`execution`](#effect_tag_EXECUTION)
When disabled, any non-passing test will cause the entire build to stop. By default all tests are run, even if some do not pass.
Tags: [`execution`](#effect_tag_EXECUTION)
Specifies which strategy to use when running tests.
Tags: [`execution`](#effect_tag_EXECUTION)
Specifies the base temporary directory for 'bazel test' to use.
Options that trigger optimizations of the build time
If greater than 0, configures Bazel to cache file digests in memory based on their metadata instead of recomputing the digests from disk every time they are needed. Setting this to 0 ensures correctness because not all file changes can be noted from file metadata. When not 0, the number indicates the size of the cache as the number of file digests to be cached.
Active directories for remote analysis caching. Specify as comma-separated workspace root-relative paths.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Enables the experimental local execution scheduling based on CPU load, not estimation of actions one by one. Experimental scheduling have showed the large benefit on a large local builds on a powerful machines with the large number of cores. Recommended to use with --local\_resources=cpu=HOST\_CPUS
Tags: [`execution`](#effect_tag_EXECUTION)
Takes a list of OS signal numbers. If a local branch of dynamic execution gets killed with any of these signals, the remote branch will be allowed to finish instead. For persistent workers, this only affects signals that kill the worker process.
Tags: [`execution`](#effect_tag_EXECUTION)
Enables the experimental local execution scheduling based on memory load, not estimation of actions one by one.
Tags: [`execution`](#effect_tag_EXECUTION)
Set the number of resources available to Bazel. Takes in an assignment to a float or HOST\_RAM/HOST\_CPUS, optionally followed by \[-|*]\ (eg. memory=HOST\_RAM*.5 to use half the available RAM). Can be used multiple times to specify multiple types of resources. Bazel will limit concurrently running actions based on the available resources and the resources required. Tests can declare the amount of resources they need by using a tag of the "resources:\:\" format.
*May be used multiple times; values are accumulated.*
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Options that affect the verbosity, format or location of logging
The maximum number of times Bazel should retry uploading a build event.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
When displaying subcommands (--subcommands) or printing the command line of a failed action (--verbose\_failures), expand the contents of param files. When enabled, param file references like @path/to/param\_file are replaced with the actual arguments they contain.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether to publish `TargetSummary` events.
No-op.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specify how an output group's files will be represented in `TargetComplete`/`AspectComplete`
BEP events. Values are an assignment of an output group name to one of
`NAMED_SET_OF_FILES_ONLY`, `INLINE_ONLY`, or `BOTH`. The default value is
`NAMED_SET_OF_FILES_ONLY`. If an output group is repeated, the final value to
appear is used. The default value sets the mode for coverage artifacts to BOTH:
`--experimental_build_event_output_group_mode=baseline.lcov=both`
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Initial, minimum delay for exponential backoff retries when BEP upload fails. (exponent: 1.6)
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Selects how to upload artifacts referenced in the build event protocol. In Bazel
the valid options include `local` and `remote`. The default value is `local`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, Bazel will print more verbose messages about the Docker sandbox strategy.
Tags: [`execution`](#effect_tag_EXECUTION)
If materializing param files, do so with direct writes to disk.
Tags: [`execution`](#effect_tag_EXECUTION)
Whether to include the command-line residue in run build events which could contain the residue. By default, the residue is not included in run command build events that could contain the residue.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Stream log file uploads directly to the remote storage rather than writing them to disk.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Causes the build system to explain each executed step of the build. The explanation is written to the specified log file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use this to suppress generation of the legacy `important_outputs` field in the
`TargetComplete` event. `important_outputs` are required for Bazel to ResultStore/BTX
integration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Writes intermediate parameter files to output tree even when using remote action execution or caching. Useful when debugging actions. This is implied by --subcommands and --verbose\_failures.
Tags: [`execution`](#effect_tag_EXECUTION)
When discarding the analysis cache due to a change in the build options, displays up to the given number of changed option names. If the number given is -1, all changed options will be displayed.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Specifies maximum per-test-log size that can be emitted when --test\_output is 'errors' or 'all'. Useful for avoiding overwhelming the output with excessively noisy test output. The test header is included in the log size. Negative values imply no limit. Output is all or nothing.
Tags: [`test_runner`](#effect_tag_TEST_RUNNER), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`execution`](#effect_tag_EXECUTION)
Only shows warnings and action outputs for rules with a name matching the provided regular expression.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The number of seconds to wait between reports on still running jobs. The
default value 0 means the first report will be printed after 10
seconds, then 30 seconds and after that progress is reported once every minute.
When `--curses` is enabled, progress is reported every second.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Choose when to print remote execution messages. Valid values are `failure`, to print only on failures, `success` to print only on successes and `all` to print always.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Enables debugging features for the sandboxing feature. This includes two things: first, the sandbox root contents are left untouched after a build; and second, prints extra debugging information on execution. This can help developers of Bazel or Starlark rules with debugging failures due to missing input files, etc.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Show the results of the build. For each target, state whether or not it was brought
up-to-date, and if so, a list of output files that were built. The printed files
are convenient strings for copy+pasting to the shell, to execute them.
This option requires an integer argument, which is the threshold number of targets
above which result information is not printed. Thus zero causes suppression of
the message and `MAX_INT` causes printing of the result to occur always. The
default is one.
If nothing was built for a target its results may be omitted to keep the output
under the threshold.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-s`
Display the subcommands executed during a build. Related flags: --execution\_log\_json\_file, --execution\_log\_binary\_file (for logging subcommands to a file in a tool-friendly format).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Specifies desired output mode. Not to be confused with `--test_summary` which controls
the test summary printed on command completion.
Valid values are;
* `summary` (default) to print summaries for failed tests,
* `errors` to also print test logs for failed tests,
* `all` to print summaries and logs for all tests and
* `streamed` to output logs for all tests in real time (this will force tests to be
executed locally one at a time via `--test_strategy=exclusive`, disabling parallel
execution and sharding. For parallel execution of multiple tests, use `errors` or
`all`).
Tags: [`test_runner`](#effect_tag_TEST_RUNNER), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`execution`](#effect_tag_EXECUTION)
Specifies the desired format of the test summary. Valid values are;
* `short` to list all tests that ran to completion.
* `short_uncached` to list tests that ran to completion, omitting cached tests.
* `terse` to list only failed and flaky tests.
* `detailed` to list tests that ran to completion and their test cases.
* `detailed_uncached` to list tests that ran to completion and their test cases,
omitting cached tests.
* `testcase` to print summary in test case resolution without detailed information about
failed test cases.
* `none` to omit the summary.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If a command fails, print out the full command line.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Specifies the values of the command-line aspects parameters. Each parameter value is
specified via `=`, for example `my_param=my_val` where
`my_param` is a parameter of some aspect in `--aspects` list or required by an
aspect in the list. This option can be used multiple times. However, it is not
allowed to assign values to the same parameter more than once.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set, build will read patterns from the file named here, rather than on the command line. It is an error to specify a file here as well as command-line patterns.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
If set, build will evaluate the query expression and build the resulting targets. Example: --target\_query='deps(//foo) - deps(//bar)'. May be combined with command-line target patterns. Cannot be used with --target\_pattern\_file or --target\_query\_file.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
If set, build will read a query expression from the file named here and build the resulting targets. May be combined with command-line target patterns. Cannot be used with --target\_pattern\_file or --target\_query.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Remote caching and execution options
Fail if regenerating a rewound action changes its recorded output contents. This detects nondeterministic regeneration before dependent actions consume the new result. Best effort: requires previous output metadata and may miss changes when another shared action regenerates the outputs.
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Specifies the strategy for the circuit breaker to use. Available strategies are "failure". On invalid value for the option the behavior same as the option is not set.
Tags: [`execution`](#effect_tag_EXECUTION)
The maximum number of times action rewinding will try to recover the same lost input (or top-level output) for the same action before giving up and failing the build. Set this lower to fail fast on an unstable remote cache instead of repeatedly rewinding a single lost input; 0 fails on the first lost input. Only takes effect when --rewind\_lost\_inputs is enabled.
Tags: [`execution`](#effect_tag_EXECUTION)
If enabled, large blobs are split into content-defined chunks and uploaded/downloaded in chunks, enabling deduplication across blobs. The server must advertise SplitBlob/SpliceBlob RPCs and the parameters of the chunking function selected by --experimental\_remote\_cache\_chunking\_function in its capabilities.
Tags: [`experimental`](#metadata_tag_EXPERIMENTAL)
The content-defined chunking function used to split large blobs when --experimental\_remote\_cache\_chunking is enabled. If set to 'auto' (the default), the function is negotiated with the server: FastCDC 2020 is used if the server advertises it, otherwise RepMaxCDC. Set to 'fast\_cdc\_2020' or 'rep\_max\_cdc' to require a specific function, in which case the server must advertise the parameters of that function in its capabilities. All clients sharing a cache should use the same function to maximize chunk reuse.
Tags: [`experimental`](#metadata_tag_EXPERIMENTAL)
The minimum blob size required to compress/decompress with zstd. Ineffectual unless --remote\_cache\_compression is set.
The maximum number of attempts to retry if the build encountered a transient remote cache error that would otherwise fail the build. Applies for example when artifacts are evicted from the remote cache, or in certain cache failure conditions. A new invocation id will be generated for each attempt.
Tags: [`execution`](#effect_tag_EXECUTION)
If set to true, Bazel will extend the lease for outputs of remote actions during the build by sending `FindMissingBlobs` calls periodically to remote cache. The frequency is based on the value of `--experimental_remote_cache_ttl`.
The guaranteed minimal TTL of blobs in the remote cache after their digests are recently referenced e.g. by an ActionResult or FindMissingBlobs. Bazel does several optimizations based on the blobs' TTL e.g. doesn't repeatedly call GetActionResult in an incremental build. The value should be set slightly less than the real TTL since there is a gap between when the server returns the digests and when Bazel receives them.
Tags: [`execution`](#effect_tag_EXECUTION)
A path to a directory where the corrupted outputs will be captured to. An empty value resets the flag to its default.
The delay after the failure circuit breaker trips before it allows a single trial remote call to probe whether the remote cache/executor has recovered. If the trial succeeds the breaker closes and normal calls resume; otherwise it re-opens and waits again before the next trial. A zero or negative value (the default) disables recovery, so a tripped breaker stays open for the remainder of the build. Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds. Only takes effect with --experimental\_circuit\_breaker\_strategy=failure.
Tags: [`execution`](#effect_tag_EXECUTION)
If set to true, discard in-memory copies of the input root's Merkle tree and associated input mappings during calls to GetActionResult() and Execute(). This reduces memory usage significantly, but does require Bazel to recompute them upon remote cache misses and retries.
Sets the allowed number of failure rate in percentage for a specific time window after which it stops calling to the remote cache/executor. By default the value is 10. Setting this to 0 means no limitation.
Tags: [`execution`](#effect_tag_EXECUTION)
The interval in which the failure rate of the remote requests are computed. On zero or negative value the failure duration is computed the whole duration of the execution.Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds.
Tags: [`execution`](#effect_tag_EXECUTION)
If set to true, Bazel will mark inputs as tool inputs for the remote executor. This can be used to implement remote persistent workers.
The minimum number of remote calls that must be observed within the failure window before the circuit breaker computes the failure rate. The rate is computed (and the breaker may trip) once either this many total calls or --experimental\_remote\_min\_fail\_count\_to\_compute\_failure\_rate failures are observed. Only takes effect with --experimental\_circuit\_breaker\_strategy=failure.
Tags: [`execution`](#effect_tag_EXECUTION)
The minimum number of failed remote calls that must be observed within the failure window before the circuit breaker computes the failure rate. The rate is computed (and the breaker may trip) once either this many failures or --experimental\_remote\_min\_call\_count\_to\_compute\_failure\_rate total calls are observed. Only takes effect with --experimental\_circuit\_breaker\_strategy=failure.
Tags: [`execution`](#effect_tag_EXECUTION)
HOST or HOST:PORT of a remote output service endpoint. The supported schemes are grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. Specify grpc:// or unix: scheme to disable TLS. An empty value resets the flag to its default.
The path under which the contents of output directories managed by the --experimental\_remote\_output\_service are placed. The actual output directory used by a build will be a descendant of this path and determined by the output service.
If set to true, enforce that all actions that can run remotely are cached, or else fail the build. This is useful to troubleshoot non-determinism issues as it allows checking whether actions that should be cached are actually cached without spuriously injecting new results into the cache.
Enables remote cache key scrubbing with the supplied configuration file, which must be a protocol buffer in text format (see src/main/protobuf/remote\_scrubbing.proto).
This feature is intended to facilitate sharing a remote/disk cache between actions executing on different platforms but targeting the same platform. It should be used with extreme care, as improper settings may cause accidental sharing of cache entries and result in incorrect builds.
Scrubbing does not affect how an action is executed, only how its remote/disk cache key is computed for the purpose of retrieving or storing an action result. Scrubbed actions are incompatible with remote execution, and will always be executed locally instead.
Modifying the scrubbing configuration does not invalidate outputs present in the local filesystem or internal caches; a clean build is required to reexecute affected actions.
In order to successfully use this feature, you likely want to set a custom --host\_platform (to normalize output prefixes). An empty value disables scrubbing.
Set this to 'full' to enable checking the ctime of all input files of an action before uploading it to a remote cache. There may be cases where the Linux kernel delays writing of files, which could cause false positives. The default is 'lite', which only checks source files in the main repository. Setting this to 'off' disables all checks. This is not recommended, as the cache may be polluted when a source file is changed while an action that takes it as an input is executing.
Tags: [`execution`](#effect_tag_EXECUTION)
Whether --remote\_local\_fallback applies to --remote\_cache.
Whether to accept remotely cached action results.
If set to 'all', all local outputs referenced by BEP are uploaded to remote cache.
If set to 'minimal', local outputs referenced by BEP are not uploaded to the remote cache, except for files that are important to the consumers of BEP (e.g. test logs and timing profile). bytestream:// scheme is always used for the uri of files even if they are missing from remote cache.
Default to 'minimal'.
The hostname and instance name to be used in bytestream:// URIs that are written into build event streams. This option can be set when builds are performed using a proxy, which causes the values of --remote\_executor and --remote\_instance\_name to no longer correspond to the canonical name of the remote execution service. When not set, it will default to "\$\{hostname}/\$\{instance\_name}". An empty value resets the flag to its default.
A URI of a caching endpoint. The supported schemes are http, https, grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. Specify grpc://, http\:// or unix: scheme to disable TLS. An empty value resets the flag to its default. See [https://bazel.build/remote/caching](https://bazel.build/remote/caching)
If true, uploading of action results to a disk or remote cache will happen in the background instead of blocking the completion of an action. Some actions are incompatible with background uploads, and may still block even when this flag is set.
If enabled, compress/decompress cache blobs with zstd when their size is at least --experimental\_remote\_cache\_compression\_threshold.
Specify a header that will be included in cache requests: --remote\_cache\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Set the default exec properties to be used as the remote execution platform if an execution platform does not already set exec\_properties.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Force remote build outputs whose path matches this pattern to be downloaded, irrespective of --remote\_download\_outputs. Multiple patterns may be specified by repeating this flag.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
A Remote Asset API endpoint URI, to be used as a remote download proxy. The supported schemes are grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. An empty value resets the flag to its default. See: [https://github.com/bazelbuild/remote-apis/blob/master/build/bazel/remote/asset/v1/remote\_asset.proto](https://github.com/bazelbuild/remote-apis/blob/master/build/bazel/remote/asset/v1/remote_asset.proto)
Specify a header that will be included in remote downloader requests: --remote\_downloader\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Whether to fall back to the local downloader if remote downloader fails.
Whether to propagate credentials from netrc and credential helper to the remote downloader server. The server implementation needs to support the new `http_header_url::` qualifier where the `` is a 0-based position of the URL inside the FetchBlobRequest's `uris` field. The URL-specific headers should take precedence over the global headers.
Specify a header that will be included in execution requests: --remote\_exec\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
The relative priority of actions to be executed remotely. The semantics of the particular priority values are server-dependent.
HOST or HOST:PORT of a remote execution endpoint. The supported schemes are grpc, grpcs (grpc with TLS enabled) and unix (local UNIX sockets). If no scheme is provided Bazel will default to grpcs. Specify grpc:// or unix: scheme to disable TLS. An empty value resets the flag to its default.
The maximum amount of time a remote gRPC download may go without receiving response data before Bazel cancels and retries the download. This applies to ByteStream Read. The value 0 disables the timeout. If the unit is omitted, the value is interpreted as seconds.
If specified, a path to a file to log gRPC call related details. This log consists of a sequence of serialized com.google.devtools.build.lib.remote.logging.RemoteExecutionLog.LogEntry protobufs with each message prefixed by a varint denoting the size of the following serialized protobuf message, as performed by the method LogEntry.writeDelimitedTo(OutputStream).
Path to a gRPC service config JSON file for remote gRPC channels. This replaces the service config Bazel generates from --remote\_timeout. Only a subset of the gRPC service config JSON schema is supported: top-level methodConfig entries with name objects containing service and optional method, plus timeout. Other service config fields are rejected and may be supported in the future.
Specify a header that will be included in requests: --remote\_header=Name=Value. Multiple headers can be passed by specifying the flag multiple times. Multiple values for the same name will be converted to a comma-separated list.
*May be used multiple times; values are accumulated.*
Tags: [`fully_redacted_in_logs`](#metadata_tag_FULLY_REDACTED_IN_LOGS)
Value to pass as instance\_name in the remote execution API.
Whether to fall back to standalone local execution strategy if remote execution fails.
Deprecated. See [https://github.com/bazelbuild/bazel/issues/7480](https://github.com/bazelbuild/bazel/issues/7480) for details.
Tags: [`deprecated`](#metadata_tag_DEPRECATED)
Limit the max number of concurrent requests per gRPC connection. By default the value is 100.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Limit the max number of concurrent connections to remote cache/executor. By default the value is 100. Setting this to 0 means no limitation.
For HTTP remote cache, one TCP connection could handle one request at one time, so Bazel could make up to --remote\_max\_connections concurrent requests.
For gRPC remote cache/executor, one gRPC channel could usually handle 100+ concurrent requests (controlled by --remote\_max\_concurrency\_per\_connection), so Bazel could make around `--remote_max_connections * 100` concurrent requests.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
Connect to the remote cache through a proxy. Currently this flag can only be used to configure a Unix domain socket (unix:/path/to/socket). An empty value resets the flag to its default.
The relative priority of remote actions to be stored in remote cache. The semantics of the particular priority values are server-dependent.
The maximum number of attempts to retry a transient error. If set to 0, retries are disabled.
The maximum backoff delay between remote retry attempts. Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds.
The maximum amount of time to wait for remote execution and cache calls. For the REST cache, this is both the connect and the read timeout. Following units can be used: Days (d), hours (h), minutes (m), seconds (s), and milliseconds (ms). If the unit is omitted, the value is interpreted as seconds.
Whether to upload locally executed action results to the remote cache if the remote cache supports it and the user is authorized to do so.
If set to true, Bazel will compute the hash sum of all remote downloads and discard the remotely cached values if they don't match the expected value.
Whether to use action rewinding to recover from lost inputs.
Tags: [`execution`](#effect_tag_EXECUTION)
Miscellaneous options, not otherwise categorized.
If discarding the analysis cache due to a change in the build system, setting this
option to false will cause bazel to exit, rather than continuing with the build.
This option has no effect when `--discard_analysis_cache` is also set.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If --output\_filter is not specified, then the value for this option is used create a filter automatically. Allowed values are 'none' (filter nothing / show everything), 'all' (filter everything / show nothing), 'packages' (include output from rules in packages mentioned on the Blaze command line), and 'subpackages' (like 'packages', but also include subpackages). For the 'packages' and 'subpackages' values //java/foo and //javatests/foo are treated as one package)'.
Forces targets tagged 'manual' to be built. Despite the flag name, this option applies to all targets (both test and non-test targets) matching the pattern. Targets tagged 'manual' are excluded from processing by default; this option forces them to be built (tests are built but not executed).
Specifies a comma-separated list of tags. Each tag can be optionally preceded with '-' to specify excluded tags. Only those targets will be built that contain at least one included tag and do not contain any excluded tags. This option does not affect the set of tests executed with the 'test' command; those are be governed by the test filtering options, for example '--test\_tag\_filters'
If specified, only \*\_test and test\_suite rules will be built and other targets specified on the command line will be ignored. By default everything that was requested will be built.
Specifies desired cumulative coverage report type. At this point only LCOV is supported.
Compile a single dependency of the argument files. This is useful for syntax checking source files in IDEs, for example, by rebuilding a single target that depends on the source file to detect errors as early as possible in the edit/build/test cycle. This argument affects the way all non-flag arguments are interpreted; instead of being targets to build they are source filenames. For each source filename an arbitrary target that depends on it will be built.
A comma-separated list of names of packages which the build system will consider non-existent, even if they are visible somewhere on the package path.
Use this option when deleting a subpackage 'x/y' of an existing package 'x'. For example, after deleting x/y/BUILD in your client, the build system may complain if it encounters a label '//x:y/z' if that is still provided by another package\_path entry. Specifying --deleted\_packages x/y avoids this problem.
*May be used multiple times; values are accumulated.*
Discard the analysis cache immediately after the analysis phase completes. Reduces memory usage by \~10%, but makes further incremental builds slower.
A path to a directory where Bazel can read and write actions and action outputs. If the directory does not exist, it will be created. Use --disk\_cache with no value (or --disk\_cache=true) to use a default location under the output user root (\/cache/disk). Use --nodisk\_cache or --disk\_cache=false to disable.
How long the server must remain idle before a garbage collection of the disk cache occurs. To specify the garbage collection policy, set --disk\_cache\_gc\_max\_size and/or --disk\_cache\_gc\_max\_age.
If set to a positive value, the disk cache will be periodically garbage collected to remove entries older than this age. If set in conjunction with --disk\_cache\_gc\_max\_size, both criteria are applied. Garbage collection occurrs in the background once the server has become idle, as determined by the --disk\_cache\_gc\_idle\_delay flag.
If set to a positive value, the disk cache will be periodically garbage collected to stay under this size. If set in conjunction with --disk\_cache\_gc\_max\_age, both criteria are applied. Garbage collection occurrs in the background once the server has become idle, as determined by the --disk\_cache\_gc\_idle\_delay flag.
Embed source control revision or release label in binary
Log the executed spawns into this file as length-delimited SpawnExec protos, according to src/main/protobuf/spawn.proto. Prefer --execution\_log\_compact\_file, which is significantly smaller and cheaper to produce. The flag accepts boolean and string values. If string, it represents a local path. If true, then --experimental\_stream\_log\_file\_uploads must be set, whereby it will stream the execution log to remote storage. If false, then logging to the execution log is disabled. Related flags: --execution\_log\_compact\_file (compact format; mutually exclusive), --execution\_log\_json\_file (text JSON format; mutually exclusive), --execution\_log\_sort (whether to sort the execution log), --subcommands (for displaying subcommands in terminal output).
Log the executed spawns into this file as length-delimited ExecLogEntry protos, according to src/main/protobuf/spawn.proto. The entire file is zstd compressed. The flag accepts boolean and string values. If string, it represents a local path. If true, then --experimental\_stream\_log\_file\_uploads must be set, whereby it will stream the execution log to remote storage. If false, then logging to the execution log is disabled. Related flags: --execution\_log\_binary\_file (binary protobuf format; mutually exclusive), --execution\_log\_json\_file (text JSON format; mutually exclusive), --subcommands (for displaying subcommands in terminal output).
Log the executed spawns into this file as newline-delimited JSON representations of SpawnExec protos, according to src/main/protobuf/spawn.proto. Prefer --execution\_log\_compact\_file, which is significantly smaller and cheaper to produce. The flag accepts boolean and string values. If string, it represents a local path. If true, then --experimental\_stream\_log\_file\_uploads must be set, whereby it will stream the execution log to remote storage. If false, then logging to the execution log is disabled. Related flags: --execution\_log\_compact\_file (compact format; mutually exclusive), --execution\_log\_binary\_file (binary protobuf format; mutually exclusive), --execution\_log\_sort (whether to sort the execution log), --subcommands (for displaying subcommands in terminal output).
Filter the execution log by mnemonic. Only spawns with a matching mnemonic will be logged. Supports a comma-separated list of regexes, with optional '-' prefix for exclusions. The default is to log every spawn.
Whether to sort the execution log, making it easier to compare logs across invocations. Set to false to avoid potentially significant CPU and memory usage at the end of the invocation, at the cost of producing the log in nondeterministic execution order. Only applies to the binary and JSON formats; the compact format is never sorted.
Expand test\_suite targets into their constituent tests before analysis. When this flag is turned on (the default), negative target patterns will apply to the tests belonging to the test suite, otherwise they will not. Turning off this flag is useful when top-level aspects are applied at command line: then they can analyze test\_suite targets.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Filters set of targets to schedule extra\_actions for.
Deprecated in favor of aspects. Only schedules extra\_actions for top level targets.
Enable dynamic execution by running actions locally and remotely in parallel. Bazel spawns each action locally and remotely and picks the one that completes first. If an action supports workers, the local action will be run in the persistent worker mode. To enable dynamic execution for an individual action mnemonic, use the `--internal_spawn_scheduler` and `--strategy==dynamic` flags instead.
Expands to:
* `--internal_spawn_scheduler`
* `--spawn_strategy=dynamic`
Tags: [`deprecated`](#metadata_tag_DEPRECATED)
Allows the command to fetch external dependencies. If set to false, the command will utilize any cached version of the dependency, and if none exists, the command will result in failure.
Time to wait between terminating a local process due to timeout and forcefully shutting it down.
A colon-separated list of where to look for packages. Elements beginning with '%workspace%' are relative to the enclosing workspace. If omitted or empty, the default is the output of 'bazel info default-package-path'.
If enabled, causes Bazel to print "Loading package:" messages.
Specifies a comma-separated list of test languages. Each language can be optionally preceded with '-' to specify excluded languages. Only those test targets will be found that are written in the specified languages. The name used for each language should be the same as the language prefix in the \*\_test rule, e.g. one of 'cc', 'java', 'py', etc. This option affects --build\_tests\_only behavior and the test command.
Specifies a comma-separated list of test sizes. Each size can be optionally preceded with '-' to specify excluded sizes. Only those test targets will be found that contain at least one included size and do not contain any excluded sizes. This option affects --build\_tests\_only behavior and the test command.
Specifies a comma-separated list of test tags. Each tag can be optionally preceded with '-' to specify excluded tags. Only those test targets will be found that contain at least one included tag and do not contain any excluded tags. This option affects --build\_tests\_only behavior and the test command.
Specifies a comma-separated list of test timeouts. Each timeout can be optionally preceded with '-' to specify excluded timeouts. Only those test targets will be found that contain at least one included timeout and do not contain any excluded timeouts. This option affects --build\_tests\_only behavior and the test command.
A command invoked at the beginning of the build to provide status
information about the workspace in the form of key/value pairs.
See the User's Manual for the full specification. Also see
`scripts/get_workspace_status.sh` for an example.
Options that control build execution
Whether to make source manifest actions remotable
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel will run coverage postprocessing for test in a new spawn.
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Add or remove keys from an action's execution info based on action mnemonic.
Applies only to actions which support execution info. Many common actions
support execution info, e.g. Genrule, CppCompile, Javac, StarlarkAction,
TestRunner. When specifying multiple values, order matters because
many regexes may apply to the same mnemonic.
Syntax: `regex=[+-]key,regex=[+-]key,...`.
Examples:
* `.*=+x,.*=-y,.*=+z` adds `x` and `z` to, and removes `y` from, the execution info for all actions.
* `Genrule=+requires-x` adds `requires-x` to the execution info for all Genrule actions.
* `(?!Genrule).*=-requires-x` removes `requires-x` from the execution info for all non-Genrule actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that configure the toolchain used for action execution
Sets the platforms that android\_binary targets use. If multiple platforms are specified, then the binary is a fat APKs, which contains native binaries for each specified target platform.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Specifies a suffix to be added to the configuration directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The C++ compiler to use for compiling the target.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION)
Location of the binary that is used to postprocess raw coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:lcov_merger`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of the binary that is used to generate coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:coverage_report_generator`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of support files that are required on the inputs of every test action
that collects code coverage. Defaults to `//tools/test:coverage_support`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies a custom malloc implementation. This setting overrides malloc attributes in build rules.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, add a "requires-xcode:\{version}" execution requirement to every Xcode action. If the Xcode version has a hyphenated label, also add a "requires-xcode-label:\{version\_label}" execution requirement.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use the most recent Xcode that is available both locally and remotely. If false, or if there are no mutual available versions, use the local Xcode version selected via xcode-select.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
The platforms that are available as execution platforms to run actions.
Platforms can be specified by exact target, or as a target pattern.
These platforms will be considered before those declared in the `WORKSPACE` file by
`register_execution_platforms()`. This option may only be set once; later
instances will override earlier flag settings.
Tags: [`execution`](#effect_tag_EXECUTION)
The toolchain rules to be considered during toolchain resolution.
Toolchains can be specified by exact target, or as a target pattern.
These toolchains will be considered before those declared in the `WORKSPACE` file
by `register_toolchains()`.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
A label to a checked-in libc library. The default value is selected by the crosstool toolchain, and you almost never need to override it.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If specified, this setting overrides the libc top-level directory (--grte\_top) for the exec configuration.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The label of a platform rule that describes the host system.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If enabled, `bazel test --run_under=//:runner` builds `//:runner` in the exec
configuration. If disabled, it builds `//:runner` in the target configuration.
Bazel executes tests on exec machines, so the former is more correct. This
doesn't affect `bazel run`, which always builds `--run_under=//foo` in the
target configuration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Whether to emit a strip action as part of objc linking.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not enable 'host' and 'nonhost' features in the c++ toolchain (see [https://github.com/bazelbuild/bazel/issues/7407](https://github.com/bazelbuild/bazel/issues/7407) for more information).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not link library dependencies as whole archive by default (see [https://github.com/bazelbuild/bazel/issues/7362](https://github.com/bazelbuild/bazel/issues/7362) for migration instructions).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, strip action for executables will use flag -x, which does not break dynamic symbol resolution.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Use interface shared objects if supported by the toolchain. All ELF toolchains currently support this setting.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The minimum OS version which your compilation targets.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The location of a mapping file that describes which platform to use if none is set or
which flags to set when a platform already exists. Must be relative to the main
workspace root. Defaults to `platform_mappings` (a file directly under the
workspace root).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
The labels of the platform rules describing the target platforms for the current command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, uses Xcode of the given version for relevant build actions. If unspecified, uses the executor default version of Xcode.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
The label of the xcode\_config rule to be used for selecting the Xcode version in the build configuration.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that control the output of the command
Whether to generate debug symbol(.dSYM) file(s).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, build runfiles symlink forests for all targets. If false, write them only when required by a local action, test or run command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, write runfiles manifests for all targets. If false, omit them. Local tests will fail to run when false.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, when building C++ tests statically and with fission the .dwp file for the test binary will be automatically built as well.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the suffixes of header files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Sets the suffixes of source files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Pass the --include\_source\_info flag when building a proto\_library. This results in vastly larger descriptors that include information about the original location of each decl in the source file as well as surrounding comments.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Save the state of enabled and requested feautres as an output of compilation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Specifies which compilation modes use fission for C++ compilations and links. May be any combination of \{'fastbuild', 'dbg', 'opt'} or the special values 'yes' to enable all modes and 'no' to disable all modes.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, native rules add `DefaultInfo.files` of data dependencies to their runfiles,
which matches the recommended behavior for Starlark rules ([runfiles features to avoid](https://bazel.build/extending/rules#runfiles_features_to_avoid)).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, the `{binary}.repo_mapping` file emits a module extension's repo mapping
only once instead of once for each repo generated by the extension that
contributes runfiles.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
List of flags for which the use in `select()` is disabled.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If true, runfiles of targets listed in the srcs attribute are available to targets that consume the filegroup as a data dependency.
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, when artifacts from the same target in multiple configurations are encountered
when constructing runfiles, prefer the version that matches the configuration of the
depending target. Specifically, when a target T depends on a target A in multiple
configurations, either directly or transitively, prefer the runfiles from the
version of A in the configuration that matches the configuration of T. This can happen,
for example, when a target appears in both the tools and data attributes.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Specifies whether to generate a linkmap file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, temporary outputs from gcc will be saved. These include .s files (assembler code), .i files (preprocessed C) and .ii files (preprocessed C++).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Specifies the set of environment variables available to actions with target
configuration. Variables can be either specified by `name`, in which case
the value will be taken from the invocation environment, by the `name=value`
pair which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can be used
multiple times; for options given for the same variable, the latest wins,
options for different variables accumulate.
Note that unless `--incompatible_repo_env_ignores_action_env` is true, all `name=value`
pairs will be available to repository rules.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Allowed values for the `--cpu` flag.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the order of manifests passed to the manifest merger for Android binaries. ALPHABETICAL means manifests are sorted by path relative to the execroot. ALPHABETICAL\_BY\_CONFIGURATION means manifests are sorted by paths relative to the configuration directory within the output directory. DEPENDENCY means manifests are ordered with each library's manifest coming before the manifests of its dependencies.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`execution`](#effect_tag_EXECUTION)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, Bazel will instrument code (using offline instrumentation where
possible) and will collect coverage information during tests. Only targets that
match `--instrumentation_filter` will be affected. Usually this option should
not be specified directly - `bazel coverage` command should be used instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-c`
Specify the mode the binary will be built in. Values: `fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to gcc when compiling C source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to gcc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Deprecated: this flag is not used internally by Blaze although there are legacy platform
mappings to allow for backwards compatibility. Do not use this flag, instead use
`--platforms` with an appropriate platform definition.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use CSFDO profile information to optimize compilation. Specify the absolute path name of the zip file containing the profile file, a raw or an indexed LLVM profile file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Generate binaries with context sensitive FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The cs\_fdo\_profile representing the context sensitive profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to gcc when compiling C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each `--define` option specifies an assignment for a build variable.
In case of multiple values for a variable, the last one wins.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Determines whether C++ binaries will be linked dynamically. 'default' means Bazel will choose whether to link dynamically. 'fully' means all libraries will be linked dynamically. 'off' means that all libraries will be linked in mostly static mode, the exception being dynamically linked system libraries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for propeller optimize will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for FDO will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Enable runfiles symlink tree; By default, it's off on Windows, on on other platforms.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of aspects to be applied to exec-configured targets, regardless of whether or not they are top-level targets. This is an experimental feature and is subject to change.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Use `action_listener` to attach an `extra_action` to
existing build actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Compress Java resources in APKs
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If specified, Bazel will also generate collect coverage information for generated files.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use libunwind for stack unwinding, and compile with -fomit-frame-pointer and -fasynchronous-unwind-tables.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Which model to use for where in the output tree rules write their outputs, particularly
for multi-platform / multi-configuration builds. This is highly experimental. See
[GH-6526](https://github.com/bazelbuild/bazel/issues/6526) for details. Starlark actions can opt into path mapping by adding the key
`supports-path-mapping` to the `execution_requirements` dict.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
If specified, Bazel will generate llvm-cov coverage map information rather than gcov when collect\_code\_coverage is enabled.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Please only use this flag as part of a suggested migration or testing strategy. Note
that the heuristic has known deficiencies and it is suggested to migrate to
relying on just `--override_platform_cpu_name`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Generate binaries with FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use FDO profile information to optimize compilation. Specify the name of a zip file containing a .gcda file tree, an afdo file containing an auto profile, or an LLVM profile file. This flag also accepts files specified as labels (e.g. `//foo/bar:file.afdo` - you may need to add an `exports_files` directive to the corresponding package) and labels pointing to `fdo_profile` targets. This flag will be superseded by the `fdo_profile` rule.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use cache prefetch hints.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The fdo\_profile representing the profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the target configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
See also `--host_features`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, all C++ compilations produce position-independent code ("-fPIC"), links prefer PIC pre-built libraries over non-PIC libraries, and links produce position-independent executables ("-pie").
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to actions with execution
configurations. Variables can be either specified by `name`, in which case the
value will be taken from the invocation environment, by the `name=value` pair
which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can
be used multiple times; for options given for the same variable, the latest
wins, options for different variables accumulate.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Specify the mode the tools used during the build will be built in. Values:
`fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to the C compiler when compiling C (but not C++) source files in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to the C compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The host CPU.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to C++ compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the exec configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to linker when linking tools in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible macOS version for host targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Additional options to selectively pass to the C/C++ compiler when compiling certain files in the exec configurations. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --host\_per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When enabled, an exec groups is automatically created for each toolchain used by a rule.
For this to work rule needs to specify `toolchain` parameter on its actions. For
more information, see [GH-17134](https://github.com/bazelbuild/bazel/issues/17134).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, the genfiles directory is folded into the bin directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If specified, the value of the cpu constraint (`@platforms//cpu:cpu`) of
the target platform is used to set the `$(TARGET_CPU)` make variable.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When coverage is enabled, specifies whether to consider instrumenting test rules.
When set, test rules included by `--instrumentation_filter` are instrumented.
Otherwise, test rules are always excluded from coverage instrumentation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When coverage is enabled, only rules with names included by the
specified regex-based filter will be instrumented. Rules prefixed
with '-' are excluded instead. Note that only non-test rules are
instrumented unless `--instrument_test_targets` is enabled.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible iOS version for target simulators and devices. If unspecified, uses 'ios\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures to build an ios\_application with. The result is a universal binary containing all specified architectures.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional option to pass to gcc when linking.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO backend step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO indexing step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple macOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible macOS version for targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use memprof profile.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether to perform symbol and dead-code strippings on linked binaries. Binary strippings will be performed if both this flag and --compilation\_mode=opt are specified.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional options to pass to gcc when compiling Objective-C/C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Each entry should be of the form `label=value` where label refers to a platform and values
is the desired shortname to override the platform's CPU name in `$(TARGET_CPU)`
make variable and output path. Only used when `--incompatible_target_cpu_from_platform` or
`--incompatible_bep_cpu_from_platform` is true. Has highest naming priority.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to gcc when compiling certain files. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to LTO backend (under --features=thin\_lto) when compiling certain backend objects. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns. option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_ltobackendopt=//foo/.\*.o,-//foo/bar.o\@-O0 adds the -O0 command line option to the LTO backend command line of all o files in //foo/ except bar.o.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a suffix to be added to the configuration directory.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Use Propeller profile information to optimize the build target.A propeller profile must consist of at least one of two files, a cc profile and a ld profile. This flag accepts a build label which must refer to the propeller profile input files. For example, the BUILD file that defines the label, in a/b/BUILD:propeller\_optimize( name = "propeller\_profile", cc\_profile = "propeller\_cc\_profile.txt", ld\_profile = "propeller\_ld\_profile.txt",)An exports\_files directive may have to be added to the corresponding package to make these files visible to Bazel. The option must be used as: --propeller\_optimize=//a/b:propeller\_profile
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of cc\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of ld\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Prefix to insert before the executables for the `test` and `run` commands.
If the value is `foo -bar`, and the execution command line is `test_binary -baz`,
then the final command line is `foo -bar test_binary -baz`.
This can also be a label to an executable target. Some examples are:
* `valgrind`
* `strace`
* `strace -c`
* `valgrind --quiet --num-callers=20`
* `//package:target`
* `//package:target --options`
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, native libraries that contain identical functionality will be shared among different targets
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Stamp binaries with the date, username, hostname, workspace information, etc.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether to strip binaries and shared libraries (using "-Wl,--strip-debug"). The default value of 'sometimes' means strip iff --compilation\_mode=fastbuild.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to strip when generating a '\.stripped' binary.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple tvOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible tvOS version for target simulators and devices. If unspecified, uses 'tvos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures for which to build Apple visionOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Comma-separated list of architectures for which to build Apple watchOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible watchOS version for target simulators and devices. If unspecified, uses 'watchos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use XbinaryFDO profile information to optimize compilation. Specify the name of default cross binary profile. When the option is used together with --fdo\_instrument/--fdo\_optimize/--fdo\_profile, those options will always prevail as if xbinary\_fdo is never specified.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If disabled, visibility errors in target dependencies are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Whether to desugar Java 8 bytecode before dexing.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Whether to include supported Java 8 libraries in apps for legacy devices.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Checks the environments each target is compatible with and reports errors if any target has dependencies that don't support the same environments
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable package()s to set the transitive\_visibility attribute to restrict which packages may depend on them.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, enforce that a java\_binary rule can't contain more than one version of the same class file on the classpath. This enforcement can break the build, or can just result in warnings.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If true, checks that a Java target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If enabled, check testonly for prerequisite targets that are output files by looking up the testonly of the generating rule. This matches visibility checking.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When enabled, and with experimental\_one\_version\_enforcement set to a non-NONE value, enforce one version on java\_test targets. This flag can be disabled to improve incremental test performance at the expense of missing potential one version violations.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Unless OFF, checks that a proto\_library target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Unless OFF, checks that a proto\_library target explicitly declares all targets used in 'import public' as exported.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, headers found through system include paths (-isystem) are also required to be declared.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Declares this build's target environment. Must be a label reference to an
`environment` rule. If specified, all top-level targets must be compatible with this
environment.
See also `--platforms`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Options that affect the signing outputs of a build
Implementation to use to sign APKs
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set, and compilation mode is not 'opt', objc apps will include debug entitlements when signing.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If true, disallow sdk\_frameworks and weak\_sdk\_frameworks attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, make the default value true for alwayslink attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
If true, an analysis failure of a rule target results in the target's propagation
of an instance of `AnalysisFailureInfo` containing the error description, instead
of resulting in a build failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Sets the maximum number of transitive dependencies through a rule attribute with
a `for_analysis_testing` configuration transition.
Exceeding this limit will result in a rule error.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Override the default resources amount for tests. The expected format is
`{resource}={value}`. If a single positive number is specified as `{value}`
it will override the default resources for all test sizes. If 4
comma-separated numbers are specified, they will override the resource
amount for respectively the `small`, `medium`, `large`, `enormous` test sizes.
Values can also be `HOST_RAM`/`HOST_CPU`, optionally followed
by `[-|*]{float}` (eg. `memory=HOST_RAM*.1,HOST_RAM*.2,HOST_RAM*.3,HOST_RAM*.4`).
The default test resources specified by this flag are overridden by explicit
resources specified in tags.
*May be used multiple times; values are accumulated.*
Specifies number of times to run each test. If any of those attempts fail for any
reason, the whole test is considered failed. Normally the value specified is
just an integer.
Example: `--runs_per_test=3` will run all tests 3 times.
Alternate syntax: `regex_filter@runs_per_test`. Where `runs_per_test` stands for
an integer value and `regex_filter` stands for a list of include and exclude
regular expression patterns (Also see --instrumentation\_filter).
Example: `--runs_per_test=//foo/.*,-//foo/bar/.*@3` runs all tests in `//foo/` except
those under `//foo/bar` three times. This option can be passed multiple times. The most
recently passed argument that matches takes precedence. If nothing matches,
the test is only run once.
*May be used multiple times; values are accumulated.*
Specifies additional environment variables to be injected into the test runner
environment. Variables can be either specified by `name`, in which
case its value will be read from the Bazel client environment, or by the
`name=value` pair.
Previously set variables can be unset via `=name`.
This option can be used multiple times to specify several variables.
Used only by the 'bazel test' command.
*May be used multiple times; values are accumulated.*
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Override the default test timeout values for test timeouts (in secs). If a single
positive integer value is specified it will override all categories. If 4
comma-separated integers are specified, they will override the timeouts for
`short`, `moderate`, `long` and `eternal` (in that order). In either form, a value of
-1 tells blaze to use its default timeouts for that category.
If true, undeclared test outputs will be archived in a zip file.
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Options that trigger optimizations of the build time
Whether to generate and analyze .d files.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, C++ .d files will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, the dependency (.jdeps) files generated from Java compilations will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, `--trim_test_configuration` will not trim the test configuration for rules
marked testonly=1. This is meant to reduce action conflict issues when non-test
rules depend on `cc_test` rules. No effect if `--trim_test_configuration` is
false.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set, .d files emitted by clang will be used to prune the set of inputs passed into objc compiles.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
When building a target //a:a, process headers in all targets that //a:a depends on (if header processing is enabled for the toolchain).
Tags: [`execution`](#effect_tag_EXECUTION)
When enabled, test-related options will be cleared below the top level of the build. When this flag is active, tests cannot be built as dependencies of non-test rules, but changes to test-related options will not cause non-test rules to be re-analyzed.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Options that affect the verbosity, format or location of logging
Print debug information during toolchain resolution. The flag takes a regex, which is checked against toolchain types and specific targets to see which to debug. Multiple regexes may be separated by commas, and then each regex is checked separately. Note: The output of this flag is very complex and will likely only be useful to experts in toolchain resolution.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, visibility errors include additional diagnostic information.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Sets a shorthand name for a Starlark flag. It takes a single key-value pair in the form
`{key}={value}` as an argument.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Miscellaneous options, not otherwise categorized.
Short form: `-t`
If set to `auto`, Bazel reruns a test if and only if:
* Bazel detects changes in the test or its dependencies,
* The test is marked as `external`,
* Multiple test runs were requested with `--runs_per_test`, or
* The test previously failed.
If set to `yes`, Bazel caches all test results except for tests marked as
`external`. If set to `no`, Bazel does not cache any test results.
If `on_failed` or `on_passed`, then Blaze will cancel concurrently running tests on the first
successful run with that result. This is only useful in combination with
`--runs_per_test_detects_flakes`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel fetches the entire coverage data directory for each test during a coverage run.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, coverage for clang will generate an LCOV report.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables reduced classpaths for Java compilations.
Whether to validate java\_\* sources.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The number of CPUs to reserve for Turbine.
Explicitly specify a dependency to JUnit or Hamcrest in a java\_test instead of accidentally obtaining from the TestRunner's deps. Only works for bazel right now.
The Java launcher used by tools that are executed during a build.
Additional options to pass to javac when building tools that are executed during a build.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM when building tools that are executed during the build. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
If true, exclusive tests will run with sandboxed strategy. Add `local` tag to force
an exclusive test run locally
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel uses an environment with a static value for PATH and does not
inherit `LD_LIBRARY_PATH`. Use `--action_env=ENV_VARIABLE` if you want to
inherit specific environment variables from the client, but note that doing so
can prevent cross-user caching if a shared cache is used.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Causes the Java virtual machine of a java test to wait for a connection from a JDWP-compliant debugger (such as jdb) before starting the test. Implies -test\_output=streamed.
Expands to:
* `--test_arg=--wrapper_script_flag=--debug`
* `--test_output=streamed`
* `--test_strategy=exclusive`
* `--test_timeout=9999`
* `--nocache_test_results`
Generate dependency information (for now, compile-time classpath) per Java target.
Compile ijars directly from source.
The Java language version
The Java launcher to use when building Java binaries. If this flag is set to the empty string, the JDK launcher is used. The "launcher" attribute overrides this flag.
The Java runtime version
Additional options to pass to javac.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
Specifies a binary to use to generate the list of classes that must be in the main dex when compiling legacy multidex.
Specifies a binary to use to do dexing without sharding.
Plugins to use in the build. Currently works with java\_plugin.
*May be used multiple times; values are accumulated.*
Specifies which version of ProGuard to use for code removal when building a Java binary.
The label of the proto-compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether to pass profile\_path to the proto compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
The profile to pass to the proto compiler as profile\_path. If unset, but --proto\_profile is true (the default), infers the path from --fdo\_optimize.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile C++ protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile Java protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile JavaLite protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional options to pass to the protobuf compiler.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, any shard in which at least one run/attempt passes and at least one run/attempt fails gets a FLAKY status.
Absolute path to the shell executable for Bazel to use. If this is unset, but the
`BAZEL_SH` environment variable is set on the first Bazel invocation (that starts
up a Bazel server), Bazel uses that. If neither is set, Bazel uses a hard-coded
default path depending on the operating system it runs on;
* Windows: `c:/msys64/usr/bin/bash.exe`
* FreeBSD and OpenBSD: `/usr/local/bin/bash`
* All others: `/bin/bash`.
Note that using a shell that is not compatible with `bash` may lead
to build failures or runtime failures of the generated binaries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies additional options and arguments that should be passed to the test
executable. Can be used multiple times to specify several arguments.
If multiple tests are executed, each of them will receive identical arguments.
Used only by the `bazel test` command.
*May be used multiple times; values are accumulated.*
Specifies a filter to forward to the test framework. Used to limit the tests run. Note that this does not affect which targets are built.
Forwards fail fast option to the test runner. The test runner should stop execution upon first failure.
Specify strategy for test sharding:
* `explicit` to only use sharding if the `shard_count` `BUILD` attribute is
present.
* `disabled` to never use test sharding.
* `forced=k` to enforce `k` shards for testing regardless of the `shard_count` `BUILD`
attribute.
The Java language version used to execute the tools that are needed during a build
The Java runtime version used to execute tools during the build
If enabled, this option causes Java compilation to use interface jars. This will result in faster incremental compilation, but error messages can be different.
## Canonicalize-flags Options
Inherits all options from [build](#build).
Options that control the output of the command
Output the canonical policy, after expansion and filtering. To keep the output clean, the canonicalized command arguments will NOT be shown when this option is set to true. Note that the command specified by --for\_command affects the filtered policy, and if none is specified, the default command is 'build'.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether Starlark options set to their default values are included in the output.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If incompatible\_enforce\_config\_setting\_visibility=false, this is a noop. Else, if this flag is false, any config\_setting without an explicit visibility attribute is //visibility:public. If this flag is true, config\_setting follows the same visibility logic as all other rules. See [https://github.com/bazelbuild/bazel/issues/12933](https://github.com/bazelbuild/bazel/issues/12933).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, enforce config\_setting visibility restrictions. If false, every config\_setting is visible to every target. See [https://github.com/bazelbuild/bazel/issues/12932](https://github.com/bazelbuild/bazel/issues/12932).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
The command for which the options should be canonicalized.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Applies an invocation policy to the options to be canonicalized.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Miscellaneous options, not otherwise categorized.
A comma-separated list of names of packages which the build system will consider non-existent, even if they are visible somewhere on the package path.
Use this option when deleting a subpackage 'x/y' of an existing package 'x'. For example, after deleting x/y/BUILD in your client, the build system may complain if it encounters a label '//x:y/z' if that is still provided by another package\_path entry. Specifying --deleted\_packages x/y avoids this problem.
*May be used multiple times; values are accumulated.*
Allows the command to fetch external dependencies. If set to false, the command will utilize any cached version of the dependency, and if none exists, the command will result in failure.
A colon-separated list of where to look for packages. Elements beginning with '%workspace%' are relative to the enclosing workspace. If omitted or empty, the default is the output of 'bazel info default-package-path'.
If enabled, causes Bazel to print "Loading package:" messages.
## Clean Options
Inherits all options from [build](#build).
Options that control the output of the command
If true, output cleaning is asynchronous. When this command completes, it will be safe to execute new commands in the same client, even though the deletion may continue in the background.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If true, clean removes the entire working tree for this bazel instance, which includes all bazel-created temporary and build output files, and stops the bazel server if it is running.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
If specified, clean asynchronously removes the entire working tree for this bazel instance, which includes all bazel-created temporary and build output files, and stops the bazel server if it is running. When this command completes, it will be safe to execute new commands in the same client, even though the deletion may continue in the background.
Expands to:
* `--expunge`
* `--async`
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS)
## Config Options
## Coverage Options
Inherits all options from [test](#test).
## Cquery Options
Inherits all options from [test](#test).
Options relating to query output and semantics
How to resolve aspect dependencies when the output format is one of \{xml,proto,record}. 'off' means no aspect dependencies are resolved, 'conservative' (the default) means all declared aspect dependencies are added regardless of whether they are given the rule class of direct dependencies, 'precise' means that only those aspects are added that are possibly active given the rule class of the direct dependencies. Note that precise mode requires loading other packages to evaluate a single target thus making it slower than the other modes. Also note that even precise mode is not completely precise: the decision whether to compute an aspect is decided in the analysis phase, which is not run during 'bazel query'.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If enabled, every query command emits labels as if by the Starlark `str` function applied to a `Label` instance. This is useful for tools that need to match the output of different query commands and/or labels emitted by rules. If not enabled, output formatters are free to emit apparent repository names (relative to the main repository) instead to make the output more readable.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
aquery, cquery: whether to include aspect-generated actions in the output. query: no-op (aspects are always followed).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, then the graph will be emitted 'factored', i.e. topologically-equivalent nodes will be merged together and their labels concatenated. This option is only applicable to --output=graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The maximum length of the label string for a graph node in the output. Longer labels will be truncated; -1 means no truncation. This option is only applicable to --output=graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, implicit dependencies will be included in the dependency graph over which the query operates. An implicit dependency is one that is not explicitly specified in the BUILD file but added by bazel. For cquery, this option controls filtering resolved toolchains.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
aquery, cquery: whether to include aspect-generated actions in the output. query: no-op (aspects are always followed).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, `blaze query --output=build` will output `package_group` targets.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, when outputting package\_group's `packages` attribute, the leading `//` will not be omitted.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set and --universe\_scope is unset, then a value of --universe\_scope will be inferred as the list of unique target patterns in the query expression. Note that the --universe\_scope value inferred for a query expression that uses universe-scoped functions (e.g.`allrdeps`) may not be what you want, so you should use this option only if you know what you are doing. See [https://bazel.build/reference/query#sky-query](https://bazel.build/reference/query#sky-query) for details and examples. If --universe\_scope is set, then this option's value is ignored. Note: this option applies only to `query` (i.e. not `cquery`).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether each format is terminated with \0 instead of newline.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, deps from "nodep" attributes will be included in the dependency graph over which the query operates. A common example of a "nodep" attribute is "visibility". Run and parse the output of `info build-language` to learn about all the "nodep" attributes in the build language.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Whether each format is terminated with \0 instead of newline.
Expands to:
* `--line_terminator_null=true`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The format in which the cquery results should be printed. Allowed values for cquery are: label, label\_kind, textproto, transitions, proto, streamed\_proto, jsonproto. If you select 'transitions', you also have to specify the --transitions=(lite|full) option.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
When specified, query results will be written directly to this file, and nothing will be printed to Bazel's standard output stream (stdout). In benchmarks, this is generally faster than `bazel query > file`.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, attributes whose value is not explicitly specified in the BUILD file are included; otherwise they are omitted. This option is applicable to --output=proto
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the definition\_stack proto field, which records for each rule instance the Starlark call stack at the moment the rule's class was defined.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, configurable attributes created by select() are flattened. For list types the flattened representation is a list containing each value of the select map exactly once. Scalar types are flattened to null.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Populate the source\_aspect\_name proto field of each Attribute with the source aspect that the attribute came from (empty string if it did not).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
if enabled, proto output will include information about configurations. When disabled,cquery proto output format resembles query output format.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use the starlark environment in the value of the generated \$internal\_attr\_hash attribute. This ensures that the starlark rule definition (and its transitive imports) are part of this identifier.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether or not to calculate and populate the \$internal\_attr\_hash attribute.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the instantiation call stack of each rule. Note that this requires the stack to be present
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether to output location information in proto output at all.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Comma separated list of attributes to include in output. Defaults to all attributes. Set to empty string to not output any attribute. This option is applicable to --output=proto.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the rule\_class\_key field of each rule; and for the first rule with a given rule\_class\_key, also populate its rule\_class\_info proto field. The rule\_class\_key field uniquely identifies a rule class, and the rule\_class\_info field is a Stardoc-format rule class API definition.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether or not to populate the rule\_input and rule\_output fields.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If set, query will read the query from the file named here, rather than on the command line. It is an error to specify a file here as well as a command-line query.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
If true, the location of BUILD files in xml and proto outputs will be relative. By default, the location output is an absolute path and will not be consistent across machines. You can set this option to true to have a consistent result across machines.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Shows the configuration fragments required by a rule and its transitive dependencies. This can be useful for evaluating how much a configured target graph can be trimmed.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
A Starlark expression to format each configured target in cquery's --output=starlark mode. The configured target is bound to 'target'. If neither --starlark:expr nor --starlark:file is specified, this option will default to 'str(target.label)'. It is an error to specify both --starlark:expr and --starlark:file.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The name of a file that defines a Starlark function called 'format', of one argument, that is applied to each configured target to format it as a string. It is an error to specify both --starlark:expr and --starlark:file. See help for --output=starlark for additional detail.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Query: If disabled, dependencies on 'exec configuration' will not be included in the dependency graph over which the query operates. An 'exec configuration' dependency edge, such as the one from any 'proto\_library' rule to the Protocol Compiler, usually points to a tool executed during the build rather than a part of the same 'target' program.
Cquery: If disabled, filters out all configured targets which cross an execution transition from the top-level target that discovered this configured target. That means if the top-level target is in the target configuration, only configured targets also in the target configuration will be returned. If the top-level target is in the exec configuration, only exec configured targets will be returned. This option will NOT exclude resolved toolchains.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
The format in which cquery will print transition information.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
A comma-separated set of target patterns (additive and subtractive). The query may be performed in the universe defined by the transitive closure of the specified targets. This option is used for the query and cquery commands.
For cquery, the input to this option is the targets all answers are built under and so this option may affect configurations and transitions. If this option is not specified, the top-level targets are assumed to be the targets parsed from the query expression. Note: For cquery, not specifying this option may cause the build to break if targets parsed from the query expression are not buildable with top-level options.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that control build execution
Whether to make source manifest actions remotable
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel will run coverage postprocessing for test in a new spawn.
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Add or remove keys from an action's execution info based on action mnemonic.
Applies only to actions which support execution info. Many common actions
support execution info, e.g. Genrule, CppCompile, Javac, StarlarkAction,
TestRunner. When specifying multiple values, order matters because
many regexes may apply to the same mnemonic.
Syntax: `regex=[+-]key,regex=[+-]key,...`.
Examples:
* `.*=+x,.*=-y,.*=+z` adds `x` and `z` to, and removes `y` from, the execution info for all actions.
* `Genrule=+requires-x` adds `requires-x` to the execution info for all Genrule actions.
* `(?!Genrule).*=-requires-x` removes `requires-x` from the execution info for all non-Genrule actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that configure the toolchain used for action execution
Sets the platforms that android\_binary targets use. If multiple platforms are specified, then the binary is a fat APKs, which contains native binaries for each specified target platform.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Specifies a suffix to be added to the configuration directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The C++ compiler to use for compiling the target.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION)
Location of the binary that is used to postprocess raw coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:lcov_merger`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of the binary that is used to generate coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:coverage_report_generator`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of support files that are required on the inputs of every test action
that collects code coverage. Defaults to `//tools/test:coverage_support`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies a custom malloc implementation. This setting overrides malloc attributes in build rules.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, add a "requires-xcode:\{version}" execution requirement to every Xcode action. If the Xcode version has a hyphenated label, also add a "requires-xcode-label:\{version\_label}" execution requirement.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use the most recent Xcode that is available both locally and remotely. If false, or if there are no mutual available versions, use the local Xcode version selected via xcode-select.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
The platforms that are available as execution platforms to run actions.
Platforms can be specified by exact target, or as a target pattern.
These platforms will be considered before those declared in the `WORKSPACE` file by
`register_execution_platforms()`. This option may only be set once; later
instances will override earlier flag settings.
Tags: [`execution`](#effect_tag_EXECUTION)
The toolchain rules to be considered during toolchain resolution.
Toolchains can be specified by exact target, or as a target pattern.
These toolchains will be considered before those declared in the `WORKSPACE` file
by `register_toolchains()`.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
A label to a checked-in libc library. The default value is selected by the crosstool toolchain, and you almost never need to override it.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If specified, this setting overrides the libc top-level directory (--grte\_top) for the exec configuration.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The label of a platform rule that describes the host system.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If enabled, `bazel test --run_under=//:runner` builds `//:runner` in the exec
configuration. If disabled, it builds `//:runner` in the target configuration.
Bazel executes tests on exec machines, so the former is more correct. This
doesn't affect `bazel run`, which always builds `--run_under=//foo` in the
target configuration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Whether to emit a strip action as part of objc linking.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not enable 'host' and 'nonhost' features in the c++ toolchain (see [https://github.com/bazelbuild/bazel/issues/7407](https://github.com/bazelbuild/bazel/issues/7407) for more information).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not link library dependencies as whole archive by default (see [https://github.com/bazelbuild/bazel/issues/7362](https://github.com/bazelbuild/bazel/issues/7362) for migration instructions).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, strip action for executables will use flag -x, which does not break dynamic symbol resolution.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Use interface shared objects if supported by the toolchain. All ELF toolchains currently support this setting.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The minimum OS version which your compilation targets.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The location of a mapping file that describes which platform to use if none is set or
which flags to set when a platform already exists. Must be relative to the main
workspace root. Defaults to `platform_mappings` (a file directly under the
workspace root).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
The labels of the platform rules describing the target platforms for the current command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, uses Xcode of the given version for relevant build actions. If unspecified, uses the executor default version of Xcode.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
The label of the xcode\_config rule to be used for selecting the Xcode version in the build configuration.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that control the output of the command
Whether to generate debug symbol(.dSYM) file(s).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, build runfiles symlink forests for all targets. If false, write them only when required by a local action, test or run command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, write runfiles manifests for all targets. If false, omit them. Local tests will fail to run when false.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, when building C++ tests statically and with fission the .dwp file for the test binary will be automatically built as well.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the suffixes of header files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Sets the suffixes of source files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Pass the --include\_source\_info flag when building a proto\_library. This results in vastly larger descriptors that include information about the original location of each decl in the source file as well as surrounding comments.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Save the state of enabled and requested feautres as an output of compilation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Specifies which compilation modes use fission for C++ compilations and links. May be any combination of \{'fastbuild', 'dbg', 'opt'} or the special values 'yes' to enable all modes and 'no' to disable all modes.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, native rules add `DefaultInfo.files` of data dependencies to their runfiles,
which matches the recommended behavior for Starlark rules ([runfiles features to avoid](https://bazel.build/extending/rules#runfiles_features_to_avoid)).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, the `{binary}.repo_mapping` file emits a module extension's repo mapping
only once instead of once for each repo generated by the extension that
contributes runfiles.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
List of flags for which the use in `select()` is disabled.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If true, runfiles of targets listed in the srcs attribute are available to targets that consume the filegroup as a data dependency.
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, when artifacts from the same target in multiple configurations are encountered
when constructing runfiles, prefer the version that matches the configuration of the
depending target. Specifically, when a target T depends on a target A in multiple
configurations, either directly or transitively, prefer the runfiles from the
version of A in the configuration that matches the configuration of T. This can happen,
for example, when a target appears in both the tools and data attributes.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Specifies whether to generate a linkmap file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, temporary outputs from gcc will be saved. These include .s files (assembler code), .i files (preprocessed C) and .ii files (preprocessed C++).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Specifies the set of environment variables available to actions with target
configuration. Variables can be either specified by `name`, in which case
the value will be taken from the invocation environment, by the `name=value`
pair which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can be used
multiple times; for options given for the same variable, the latest wins,
options for different variables accumulate.
Note that unless `--incompatible_repo_env_ignores_action_env` is true, all `name=value`
pairs will be available to repository rules.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Allowed values for the `--cpu` flag.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the order of manifests passed to the manifest merger for Android binaries. ALPHABETICAL means manifests are sorted by path relative to the execroot. ALPHABETICAL\_BY\_CONFIGURATION means manifests are sorted by paths relative to the configuration directory within the output directory. DEPENDENCY means manifests are ordered with each library's manifest coming before the manifests of its dependencies.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`execution`](#effect_tag_EXECUTION)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, Bazel will instrument code (using offline instrumentation where
possible) and will collect coverage information during tests. Only targets that
match `--instrumentation_filter` will be affected. Usually this option should
not be specified directly - `bazel coverage` command should be used instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-c`
Specify the mode the binary will be built in. Values: `fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to gcc when compiling C source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to gcc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Deprecated: this flag is not used internally by Blaze although there are legacy platform
mappings to allow for backwards compatibility. Do not use this flag, instead use
`--platforms` with an appropriate platform definition.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use CSFDO profile information to optimize compilation. Specify the absolute path name of the zip file containing the profile file, a raw or an indexed LLVM profile file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Generate binaries with context sensitive FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The cs\_fdo\_profile representing the context sensitive profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to gcc when compiling C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each `--define` option specifies an assignment for a build variable.
In case of multiple values for a variable, the last one wins.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Determines whether C++ binaries will be linked dynamically. 'default' means Bazel will choose whether to link dynamically. 'fully' means all libraries will be linked dynamically. 'off' means that all libraries will be linked in mostly static mode, the exception being dynamically linked system libraries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for propeller optimize will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for FDO will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Enable runfiles symlink tree; By default, it's off on Windows, on on other platforms.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of aspects to be applied to exec-configured targets, regardless of whether or not they are top-level targets. This is an experimental feature and is subject to change.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Use `action_listener` to attach an `extra_action` to
existing build actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Compress Java resources in APKs
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If specified, Bazel will also generate collect coverage information for generated files.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use libunwind for stack unwinding, and compile with -fomit-frame-pointer and -fasynchronous-unwind-tables.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Which model to use for where in the output tree rules write their outputs, particularly
for multi-platform / multi-configuration builds. This is highly experimental. See
[GH-6526](https://github.com/bazelbuild/bazel/issues/6526) for details. Starlark actions can opt into path mapping by adding the key
`supports-path-mapping` to the `execution_requirements` dict.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
If specified, Bazel will generate llvm-cov coverage map information rather than gcov when collect\_code\_coverage is enabled.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Please only use this flag as part of a suggested migration or testing strategy. Note
that the heuristic has known deficiencies and it is suggested to migrate to
relying on just `--override_platform_cpu_name`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Generate binaries with FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use FDO profile information to optimize compilation. Specify the name of a zip file containing a .gcda file tree, an afdo file containing an auto profile, or an LLVM profile file. This flag also accepts files specified as labels (e.g. `//foo/bar:file.afdo` - you may need to add an `exports_files` directive to the corresponding package) and labels pointing to `fdo_profile` targets. This flag will be superseded by the `fdo_profile` rule.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use cache prefetch hints.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The fdo\_profile representing the profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the target configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
See also `--host_features`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, all C++ compilations produce position-independent code ("-fPIC"), links prefer PIC pre-built libraries over non-PIC libraries, and links produce position-independent executables ("-pie").
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to actions with execution
configurations. Variables can be either specified by `name`, in which case the
value will be taken from the invocation environment, by the `name=value` pair
which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can
be used multiple times; for options given for the same variable, the latest
wins, options for different variables accumulate.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Specify the mode the tools used during the build will be built in. Values:
`fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to the C compiler when compiling C (but not C++) source files in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to the C compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The host CPU.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to C++ compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the exec configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to linker when linking tools in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible macOS version for host targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Additional options to selectively pass to the C/C++ compiler when compiling certain files in the exec configurations. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --host\_per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When enabled, an exec groups is automatically created for each toolchain used by a rule.
For this to work rule needs to specify `toolchain` parameter on its actions. For
more information, see [GH-17134](https://github.com/bazelbuild/bazel/issues/17134).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, the genfiles directory is folded into the bin directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If specified, the value of the cpu constraint (`@platforms//cpu:cpu`) of
the target platform is used to set the `$(TARGET_CPU)` make variable.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When coverage is enabled, specifies whether to consider instrumenting test rules.
When set, test rules included by `--instrumentation_filter` are instrumented.
Otherwise, test rules are always excluded from coverage instrumentation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When coverage is enabled, only rules with names included by the
specified regex-based filter will be instrumented. Rules prefixed
with '-' are excluded instead. Note that only non-test rules are
instrumented unless `--instrument_test_targets` is enabled.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible iOS version for target simulators and devices. If unspecified, uses 'ios\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures to build an ios\_application with. The result is a universal binary containing all specified architectures.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional option to pass to gcc when linking.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO backend step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO indexing step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple macOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible macOS version for targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use memprof profile.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether to perform symbol and dead-code strippings on linked binaries. Binary strippings will be performed if both this flag and --compilation\_mode=opt are specified.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional options to pass to gcc when compiling Objective-C/C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Each entry should be of the form `label=value` where label refers to a platform and values
is the desired shortname to override the platform's CPU name in `$(TARGET_CPU)`
make variable and output path. Only used when `--incompatible_target_cpu_from_platform` or
`--incompatible_bep_cpu_from_platform` is true. Has highest naming priority.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to gcc when compiling certain files. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to LTO backend (under --features=thin\_lto) when compiling certain backend objects. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns. option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_ltobackendopt=//foo/.\*.o,-//foo/bar.o\@-O0 adds the -O0 command line option to the LTO backend command line of all o files in //foo/ except bar.o.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a suffix to be added to the configuration directory.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Use Propeller profile information to optimize the build target.A propeller profile must consist of at least one of two files, a cc profile and a ld profile. This flag accepts a build label which must refer to the propeller profile input files. For example, the BUILD file that defines the label, in a/b/BUILD:propeller\_optimize( name = "propeller\_profile", cc\_profile = "propeller\_cc\_profile.txt", ld\_profile = "propeller\_ld\_profile.txt",)An exports\_files directive may have to be added to the corresponding package to make these files visible to Bazel. The option must be used as: --propeller\_optimize=//a/b:propeller\_profile
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of cc\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of ld\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Prefix to insert before the executables for the `test` and `run` commands.
If the value is `foo -bar`, and the execution command line is `test_binary -baz`,
then the final command line is `foo -bar test_binary -baz`.
This can also be a label to an executable target. Some examples are:
* `valgrind`
* `strace`
* `strace -c`
* `valgrind --quiet --num-callers=20`
* `//package:target`
* `//package:target --options`
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, native libraries that contain identical functionality will be shared among different targets
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Stamp binaries with the date, username, hostname, workspace information, etc.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether to strip binaries and shared libraries (using "-Wl,--strip-debug"). The default value of 'sometimes' means strip iff --compilation\_mode=fastbuild.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to strip when generating a '\.stripped' binary.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple tvOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible tvOS version for target simulators and devices. If unspecified, uses 'tvos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures for which to build Apple visionOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Comma-separated list of architectures for which to build Apple watchOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible watchOS version for target simulators and devices. If unspecified, uses 'watchos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use XbinaryFDO profile information to optimize compilation. Specify the name of default cross binary profile. When the option is used together with --fdo\_instrument/--fdo\_optimize/--fdo\_profile, those options will always prevail as if xbinary\_fdo is never specified.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If disabled, visibility errors in target dependencies are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Whether to desugar Java 8 bytecode before dexing.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Whether to include supported Java 8 libraries in apps for legacy devices.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Checks the environments each target is compatible with and reports errors if any target has dependencies that don't support the same environments
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable package()s to set the transitive\_visibility attribute to restrict which packages may depend on them.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, enforce that a java\_binary rule can't contain more than one version of the same class file on the classpath. This enforcement can break the build, or can just result in warnings.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If true, checks that a Java target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If enabled, check testonly for prerequisite targets that are output files by looking up the testonly of the generating rule. This matches visibility checking.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When enabled, and with experimental\_one\_version\_enforcement set to a non-NONE value, enforce one version on java\_test targets. This flag can be disabled to improve incremental test performance at the expense of missing potential one version violations.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Unless OFF, checks that a proto\_library target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Unless OFF, checks that a proto\_library target explicitly declares all targets used in 'import public' as exported.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, headers found through system include paths (-isystem) are also required to be declared.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Declares this build's target environment. Must be a label reference to an
`environment` rule. If specified, all top-level targets must be compatible with this
environment.
See also `--platforms`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Options that affect the signing outputs of a build
Implementation to use to sign APKs
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set, and compilation mode is not 'opt', objc apps will include debug entitlements when signing.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If true, disallow sdk\_frameworks and weak\_sdk\_frameworks attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, make the default value true for alwayslink attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
If true, an analysis failure of a rule target results in the target's propagation
of an instance of `AnalysisFailureInfo` containing the error description, instead
of resulting in a build failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Sets the maximum number of transitive dependencies through a rule attribute with
a `for_analysis_testing` configuration transition.
Exceeding this limit will result in a rule error.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Override the default resources amount for tests. The expected format is
`{resource}={value}`. If a single positive number is specified as `{value}`
it will override the default resources for all test sizes. If 4
comma-separated numbers are specified, they will override the resource
amount for respectively the `small`, `medium`, `large`, `enormous` test sizes.
Values can also be `HOST_RAM`/`HOST_CPU`, optionally followed
by `[-|*]{float}` (eg. `memory=HOST_RAM*.1,HOST_RAM*.2,HOST_RAM*.3,HOST_RAM*.4`).
The default test resources specified by this flag are overridden by explicit
resources specified in tags.
*May be used multiple times; values are accumulated.*
Specifies number of times to run each test. If any of those attempts fail for any
reason, the whole test is considered failed. Normally the value specified is
just an integer.
Example: `--runs_per_test=3` will run all tests 3 times.
Alternate syntax: `regex_filter@runs_per_test`. Where `runs_per_test` stands for
an integer value and `regex_filter` stands for a list of include and exclude
regular expression patterns (Also see --instrumentation\_filter).
Example: `--runs_per_test=//foo/.*,-//foo/bar/.*@3` runs all tests in `//foo/` except
those under `//foo/bar` three times. This option can be passed multiple times. The most
recently passed argument that matches takes precedence. If nothing matches,
the test is only run once.
*May be used multiple times; values are accumulated.*
Specifies additional environment variables to be injected into the test runner
environment. Variables can be either specified by `name`, in which
case its value will be read from the Bazel client environment, or by the
`name=value` pair.
Previously set variables can be unset via `=name`.
This option can be used multiple times to specify several variables.
Used only by the 'bazel test' command.
*May be used multiple times; values are accumulated.*
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Override the default test timeout values for test timeouts (in secs). If a single
positive integer value is specified it will override all categories. If 4
comma-separated integers are specified, they will override the timeouts for
`short`, `moderate`, `long` and `eternal` (in that order). In either form, a value of
-1 tells blaze to use its default timeouts for that category.
If true, undeclared test outputs will be archived in a zip file.
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Options that trigger optimizations of the build time
Whether to generate and analyze .d files.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, C++ .d files will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, the dependency (.jdeps) files generated from Java compilations will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, `--trim_test_configuration` will not trim the test configuration for rules
marked testonly=1. This is meant to reduce action conflict issues when non-test
rules depend on `cc_test` rules. No effect if `--trim_test_configuration` is
false.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set, .d files emitted by clang will be used to prune the set of inputs passed into objc compiles.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
When building a target //a:a, process headers in all targets that //a:a depends on (if header processing is enabled for the toolchain).
Tags: [`execution`](#effect_tag_EXECUTION)
When enabled, test-related options will be cleared below the top level of the build. When this flag is active, tests cannot be built as dependencies of non-test rules, but changes to test-related options will not cause non-test rules to be re-analyzed.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Options that affect the verbosity, format or location of logging
Print debug information during toolchain resolution. The flag takes a regex, which is checked against toolchain types and specific targets to see which to debug. Multiple regexes may be separated by commas, and then each regex is checked separately. Note: The output of this flag is very complex and will likely only be useful to experts in toolchain resolution.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, visibility errors include additional diagnostic information.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Sets a shorthand name for a Starlark flag. It takes a single key-value pair in the form
`{key}={value}` as an argument.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Miscellaneous options, not otherwise categorized.
Short form: `-t`
If set to `auto`, Bazel reruns a test if and only if:
* Bazel detects changes in the test or its dependencies,
* The test is marked as `external`,
* Multiple test runs were requested with `--runs_per_test`, or
* The test previously failed.
If set to `yes`, Bazel caches all test results except for tests marked as
`external`. If set to `no`, Bazel does not cache any test results.
If `on_failed` or `on_passed`, then Blaze will cancel concurrently running tests on the first
successful run with that result. This is only useful in combination with
`--runs_per_test_detects_flakes`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel fetches the entire coverage data directory for each test during a coverage run.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, coverage for clang will generate an LCOV report.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables reduced classpaths for Java compilations.
Whether to validate java\_\* sources.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The number of CPUs to reserve for Turbine.
Explicitly specify a dependency to JUnit or Hamcrest in a java\_test instead of accidentally obtaining from the TestRunner's deps. Only works for bazel right now.
The Java launcher used by tools that are executed during a build.
Additional options to pass to javac when building tools that are executed during a build.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM when building tools that are executed during the build. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
If true, exclusive tests will run with sandboxed strategy. Add `local` tag to force
an exclusive test run locally
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel uses an environment with a static value for PATH and does not
inherit `LD_LIBRARY_PATH`. Use `--action_env=ENV_VARIABLE` if you want to
inherit specific environment variables from the client, but note that doing so
can prevent cross-user caching if a shared cache is used.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Causes the Java virtual machine of a java test to wait for a connection from a JDWP-compliant debugger (such as jdb) before starting the test. Implies -test\_output=streamed.
Expands to:
* `--test_arg=--wrapper_script_flag=--debug`
* `--test_output=streamed`
* `--test_strategy=exclusive`
* `--test_timeout=9999`
* `--nocache_test_results`
Generate dependency information (for now, compile-time classpath) per Java target.
Compile ijars directly from source.
The Java language version
The Java launcher to use when building Java binaries. If this flag is set to the empty string, the JDK launcher is used. The "launcher" attribute overrides this flag.
The Java runtime version
Additional options to pass to javac.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
Specifies a binary to use to generate the list of classes that must be in the main dex when compiling legacy multidex.
Specifies a binary to use to do dexing without sharding.
Plugins to use in the build. Currently works with java\_plugin.
*May be used multiple times; values are accumulated.*
Specifies which version of ProGuard to use for code removal when building a Java binary.
The label of the proto-compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether to pass profile\_path to the proto compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
The profile to pass to the proto compiler as profile\_path. If unset, but --proto\_profile is true (the default), infers the path from --fdo\_optimize.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile C++ protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile Java protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile JavaLite protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional options to pass to the protobuf compiler.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, any shard in which at least one run/attempt passes and at least one run/attempt fails gets a FLAKY status.
Absolute path to the shell executable for Bazel to use. If this is unset, but the
`BAZEL_SH` environment variable is set on the first Bazel invocation (that starts
up a Bazel server), Bazel uses that. If neither is set, Bazel uses a hard-coded
default path depending on the operating system it runs on;
* Windows: `c:/msys64/usr/bin/bash.exe`
* FreeBSD and OpenBSD: `/usr/local/bin/bash`
* All others: `/bin/bash`.
Note that using a shell that is not compatible with `bash` may lead
to build failures or runtime failures of the generated binaries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies additional options and arguments that should be passed to the test
executable. Can be used multiple times to specify several arguments.
If multiple tests are executed, each of them will receive identical arguments.
Used only by the `bazel test` command.
*May be used multiple times; values are accumulated.*
Specifies a filter to forward to the test framework. Used to limit the tests run. Note that this does not affect which targets are built.
Forwards fail fast option to the test runner. The test runner should stop execution upon first failure.
Specify strategy for test sharding:
* `explicit` to only use sharding if the `shard_count` `BUILD` attribute is
present.
* `disabled` to never use test sharding.
* `forced=k` to enforce `k` shards for testing regardless of the `shard_count` `BUILD`
attribute.
The Java language version used to execute the tools that are needed during a build
The Java runtime version used to execute tools during the build
If enabled, this option causes Java compilation to use interface jars. This will result in faster incremental compilation, but error messages can be different.
## Dump Options
Options that control the output of the command
Dump action cache content.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Dump the memory use of the given Skyframe node.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Dump package cache content.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Dump rule classes.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Dump rules, including counts and memory usage (if memory is tracked).
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Key-value store for dumping remote analysis cache entries from.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Hex fingerprint of the Skycache entry to dump.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Dump the Skyframe graph.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Regex filter of SkyKey names to output. Only used with --skyframe=keys, value, deps, rdeps, function\_graph, changed.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
Dumps a pprof-compatible memory profile to the specified path. To learn more please see [https://github.com/google/pprof](https://github.com/google/pprof).
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
## Fetch Options
Inherits all options from [test](#test).
Options that control build execution
Fetches all external repositories necessary for building any target or repository.
This is the default if no other flags and arguments are provided. Only works
when `--enable_bzlmod` is on.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Short form: `-k`
Continue as much as possible after an error. While the target that failed and those that depend on it cannot be analyzed, other prerequisites of these targets can be.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Number of parallel threads to use for the loading/analysis phase.Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". "auto" sets a reasonable default based on host resources. Must be at least 1.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If incompatible\_enforce\_config\_setting\_visibility=false, this is a noop. Else, if this flag is false, any config\_setting without an explicit visibility attribute is //visibility:public. If this flag is true, config\_setting follows the same visibility logic as all other rules. See [https://github.com/bazelbuild/bazel/issues/12933](https://github.com/bazelbuild/bazel/issues/12933).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, enforce config\_setting visibility restrictions. If false, every config\_setting is visible to every target. See [https://github.com/bazelbuild/bazel/issues/12932](https://github.com/bazelbuild/bazel/issues/12932).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options relating to Bzlmod output and semantics
Only fetches repositories marked as `configure` for system-configuration purpose. Only
works when `--enable_bzlmod` is on.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Ignore existing repository if any and force fetch the repository again. Only works when
`--enable_bzlmod` is on.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Only fetches the specified repository, which can be either `@apparent_repo_name` or
`@@canonical_repo_name`. Only works when `--enable_bzlmod` is on.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Miscellaneous options, not otherwise categorized.
A comma-separated list of names of packages which the build system will consider non-existent, even if they are visible somewhere on the package path.
Use this option when deleting a subpackage 'x/y' of an existing package 'x'. For example, after deleting x/y/BUILD in your client, the build system may complain if it encounters a label '//x:y/z' if that is still provided by another package\_path entry. Specifying --deleted\_packages x/y avoids this problem.
*May be used multiple times; values are accumulated.*
Allows the command to fetch external dependencies. If set to false, the command will utilize any cached version of the dependency, and if none exists, the command will result in failure.
A colon-separated list of where to look for packages. Elements beginning with '%workspace%' are relative to the enclosing workspace. If omitted or empty, the default is the output of 'bazel info default-package-path'.
If enabled, causes Bazel to print "Loading package:" messages.
Options that control build execution
Whether to make source manifest actions remotable
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel will run coverage postprocessing for test in a new spawn.
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Add or remove keys from an action's execution info based on action mnemonic.
Applies only to actions which support execution info. Many common actions
support execution info, e.g. Genrule, CppCompile, Javac, StarlarkAction,
TestRunner. When specifying multiple values, order matters because
many regexes may apply to the same mnemonic.
Syntax: `regex=[+-]key,regex=[+-]key,...`.
Examples:
* `.*=+x,.*=-y,.*=+z` adds `x` and `z` to, and removes `y` from, the execution info for all actions.
* `Genrule=+requires-x` adds `requires-x` to the execution info for all Genrule actions.
* `(?!Genrule).*=-requires-x` removes `requires-x` from the execution info for all non-Genrule actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that configure the toolchain used for action execution
Sets the platforms that android\_binary targets use. If multiple platforms are specified, then the binary is a fat APKs, which contains native binaries for each specified target platform.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Specifies a suffix to be added to the configuration directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The C++ compiler to use for compiling the target.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION)
Location of the binary that is used to postprocess raw coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:lcov_merger`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of the binary that is used to generate coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:coverage_report_generator`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of support files that are required on the inputs of every test action
that collects code coverage. Defaults to `//tools/test:coverage_support`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies a custom malloc implementation. This setting overrides malloc attributes in build rules.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, add a "requires-xcode:\{version}" execution requirement to every Xcode action. If the Xcode version has a hyphenated label, also add a "requires-xcode-label:\{version\_label}" execution requirement.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use the most recent Xcode that is available both locally and remotely. If false, or if there are no mutual available versions, use the local Xcode version selected via xcode-select.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
The platforms that are available as execution platforms to run actions.
Platforms can be specified by exact target, or as a target pattern.
These platforms will be considered before those declared in the `WORKSPACE` file by
`register_execution_platforms()`. This option may only be set once; later
instances will override earlier flag settings.
Tags: [`execution`](#effect_tag_EXECUTION)
The toolchain rules to be considered during toolchain resolution.
Toolchains can be specified by exact target, or as a target pattern.
These toolchains will be considered before those declared in the `WORKSPACE` file
by `register_toolchains()`.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
A label to a checked-in libc library. The default value is selected by the crosstool toolchain, and you almost never need to override it.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If specified, this setting overrides the libc top-level directory (--grte\_top) for the exec configuration.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The label of a platform rule that describes the host system.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If enabled, `bazel test --run_under=//:runner` builds `//:runner` in the exec
configuration. If disabled, it builds `//:runner` in the target configuration.
Bazel executes tests on exec machines, so the former is more correct. This
doesn't affect `bazel run`, which always builds `--run_under=//foo` in the
target configuration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Whether to emit a strip action as part of objc linking.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not enable 'host' and 'nonhost' features in the c++ toolchain (see [https://github.com/bazelbuild/bazel/issues/7407](https://github.com/bazelbuild/bazel/issues/7407) for more information).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not link library dependencies as whole archive by default (see [https://github.com/bazelbuild/bazel/issues/7362](https://github.com/bazelbuild/bazel/issues/7362) for migration instructions).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, strip action for executables will use flag -x, which does not break dynamic symbol resolution.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Use interface shared objects if supported by the toolchain. All ELF toolchains currently support this setting.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The minimum OS version which your compilation targets.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The location of a mapping file that describes which platform to use if none is set or
which flags to set when a platform already exists. Must be relative to the main
workspace root. Defaults to `platform_mappings` (a file directly under the
workspace root).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
The labels of the platform rules describing the target platforms for the current command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, uses Xcode of the given version for relevant build actions. If unspecified, uses the executor default version of Xcode.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
The label of the xcode\_config rule to be used for selecting the Xcode version in the build configuration.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that control the output of the command
Whether to generate debug symbol(.dSYM) file(s).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, build runfiles symlink forests for all targets. If false, write them only when required by a local action, test or run command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, write runfiles manifests for all targets. If false, omit them. Local tests will fail to run when false.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, when building C++ tests statically and with fission the .dwp file for the test binary will be automatically built as well.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the suffixes of header files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Sets the suffixes of source files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Pass the --include\_source\_info flag when building a proto\_library. This results in vastly larger descriptors that include information about the original location of each decl in the source file as well as surrounding comments.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Save the state of enabled and requested feautres as an output of compilation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Specifies which compilation modes use fission for C++ compilations and links. May be any combination of \{'fastbuild', 'dbg', 'opt'} or the special values 'yes' to enable all modes and 'no' to disable all modes.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, native rules add `DefaultInfo.files` of data dependencies to their runfiles,
which matches the recommended behavior for Starlark rules ([runfiles features to avoid](https://bazel.build/extending/rules#runfiles_features_to_avoid)).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, the `{binary}.repo_mapping` file emits a module extension's repo mapping
only once instead of once for each repo generated by the extension that
contributes runfiles.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
List of flags for which the use in `select()` is disabled.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If true, runfiles of targets listed in the srcs attribute are available to targets that consume the filegroup as a data dependency.
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, when artifacts from the same target in multiple configurations are encountered
when constructing runfiles, prefer the version that matches the configuration of the
depending target. Specifically, when a target T depends on a target A in multiple
configurations, either directly or transitively, prefer the runfiles from the
version of A in the configuration that matches the configuration of T. This can happen,
for example, when a target appears in both the tools and data attributes.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Specifies whether to generate a linkmap file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, temporary outputs from gcc will be saved. These include .s files (assembler code), .i files (preprocessed C) and .ii files (preprocessed C++).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Specifies the set of environment variables available to actions with target
configuration. Variables can be either specified by `name`, in which case
the value will be taken from the invocation environment, by the `name=value`
pair which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can be used
multiple times; for options given for the same variable, the latest wins,
options for different variables accumulate.
Note that unless `--incompatible_repo_env_ignores_action_env` is true, all `name=value`
pairs will be available to repository rules.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Allowed values for the `--cpu` flag.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the order of manifests passed to the manifest merger for Android binaries. ALPHABETICAL means manifests are sorted by path relative to the execroot. ALPHABETICAL\_BY\_CONFIGURATION means manifests are sorted by paths relative to the configuration directory within the output directory. DEPENDENCY means manifests are ordered with each library's manifest coming before the manifests of its dependencies.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`execution`](#effect_tag_EXECUTION)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, Bazel will instrument code (using offline instrumentation where
possible) and will collect coverage information during tests. Only targets that
match `--instrumentation_filter` will be affected. Usually this option should
not be specified directly - `bazel coverage` command should be used instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-c`
Specify the mode the binary will be built in. Values: `fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to gcc when compiling C source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to gcc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Deprecated: this flag is not used internally by Blaze although there are legacy platform
mappings to allow for backwards compatibility. Do not use this flag, instead use
`--platforms` with an appropriate platform definition.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use CSFDO profile information to optimize compilation. Specify the absolute path name of the zip file containing the profile file, a raw or an indexed LLVM profile file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Generate binaries with context sensitive FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The cs\_fdo\_profile representing the context sensitive profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to gcc when compiling C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each `--define` option specifies an assignment for a build variable.
In case of multiple values for a variable, the last one wins.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Determines whether C++ binaries will be linked dynamically. 'default' means Bazel will choose whether to link dynamically. 'fully' means all libraries will be linked dynamically. 'off' means that all libraries will be linked in mostly static mode, the exception being dynamically linked system libraries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for propeller optimize will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for FDO will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Enable runfiles symlink tree; By default, it's off on Windows, on on other platforms.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of aspects to be applied to exec-configured targets, regardless of whether or not they are top-level targets. This is an experimental feature and is subject to change.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Use `action_listener` to attach an `extra_action` to
existing build actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Compress Java resources in APKs
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If specified, Bazel will also generate collect coverage information for generated files.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use libunwind for stack unwinding, and compile with -fomit-frame-pointer and -fasynchronous-unwind-tables.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Which model to use for where in the output tree rules write their outputs, particularly
for multi-platform / multi-configuration builds. This is highly experimental. See
[GH-6526](https://github.com/bazelbuild/bazel/issues/6526) for details. Starlark actions can opt into path mapping by adding the key
`supports-path-mapping` to the `execution_requirements` dict.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
If specified, Bazel will generate llvm-cov coverage map information rather than gcov when collect\_code\_coverage is enabled.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Please only use this flag as part of a suggested migration or testing strategy. Note
that the heuristic has known deficiencies and it is suggested to migrate to
relying on just `--override_platform_cpu_name`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Generate binaries with FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use FDO profile information to optimize compilation. Specify the name of a zip file containing a .gcda file tree, an afdo file containing an auto profile, or an LLVM profile file. This flag also accepts files specified as labels (e.g. `//foo/bar:file.afdo` - you may need to add an `exports_files` directive to the corresponding package) and labels pointing to `fdo_profile` targets. This flag will be superseded by the `fdo_profile` rule.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use cache prefetch hints.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The fdo\_profile representing the profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the target configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
See also `--host_features`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, all C++ compilations produce position-independent code ("-fPIC"), links prefer PIC pre-built libraries over non-PIC libraries, and links produce position-independent executables ("-pie").
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to actions with execution
configurations. Variables can be either specified by `name`, in which case the
value will be taken from the invocation environment, by the `name=value` pair
which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can
be used multiple times; for options given for the same variable, the latest
wins, options for different variables accumulate.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Specify the mode the tools used during the build will be built in. Values:
`fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to the C compiler when compiling C (but not C++) source files in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to the C compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The host CPU.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to C++ compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the exec configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to linker when linking tools in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible macOS version for host targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Additional options to selectively pass to the C/C++ compiler when compiling certain files in the exec configurations. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --host\_per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When enabled, an exec groups is automatically created for each toolchain used by a rule.
For this to work rule needs to specify `toolchain` parameter on its actions. For
more information, see [GH-17134](https://github.com/bazelbuild/bazel/issues/17134).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, the genfiles directory is folded into the bin directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If specified, the value of the cpu constraint (`@platforms//cpu:cpu`) of
the target platform is used to set the `$(TARGET_CPU)` make variable.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When coverage is enabled, specifies whether to consider instrumenting test rules.
When set, test rules included by `--instrumentation_filter` are instrumented.
Otherwise, test rules are always excluded from coverage instrumentation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When coverage is enabled, only rules with names included by the
specified regex-based filter will be instrumented. Rules prefixed
with '-' are excluded instead. Note that only non-test rules are
instrumented unless `--instrument_test_targets` is enabled.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible iOS version for target simulators and devices. If unspecified, uses 'ios\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures to build an ios\_application with. The result is a universal binary containing all specified architectures.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional option to pass to gcc when linking.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO backend step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO indexing step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple macOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible macOS version for targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use memprof profile.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether to perform symbol and dead-code strippings on linked binaries. Binary strippings will be performed if both this flag and --compilation\_mode=opt are specified.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional options to pass to gcc when compiling Objective-C/C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Each entry should be of the form `label=value` where label refers to a platform and values
is the desired shortname to override the platform's CPU name in `$(TARGET_CPU)`
make variable and output path. Only used when `--incompatible_target_cpu_from_platform` or
`--incompatible_bep_cpu_from_platform` is true. Has highest naming priority.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to gcc when compiling certain files. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to LTO backend (under --features=thin\_lto) when compiling certain backend objects. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns. option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_ltobackendopt=//foo/.\*.o,-//foo/bar.o\@-O0 adds the -O0 command line option to the LTO backend command line of all o files in //foo/ except bar.o.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a suffix to be added to the configuration directory.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Use Propeller profile information to optimize the build target.A propeller profile must consist of at least one of two files, a cc profile and a ld profile. This flag accepts a build label which must refer to the propeller profile input files. For example, the BUILD file that defines the label, in a/b/BUILD:propeller\_optimize( name = "propeller\_profile", cc\_profile = "propeller\_cc\_profile.txt", ld\_profile = "propeller\_ld\_profile.txt",)An exports\_files directive may have to be added to the corresponding package to make these files visible to Bazel. The option must be used as: --propeller\_optimize=//a/b:propeller\_profile
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of cc\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of ld\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Prefix to insert before the executables for the `test` and `run` commands.
If the value is `foo -bar`, and the execution command line is `test_binary -baz`,
then the final command line is `foo -bar test_binary -baz`.
This can also be a label to an executable target. Some examples are:
* `valgrind`
* `strace`
* `strace -c`
* `valgrind --quiet --num-callers=20`
* `//package:target`
* `//package:target --options`
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, native libraries that contain identical functionality will be shared among different targets
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Stamp binaries with the date, username, hostname, workspace information, etc.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether to strip binaries and shared libraries (using "-Wl,--strip-debug"). The default value of 'sometimes' means strip iff --compilation\_mode=fastbuild.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to strip when generating a '\.stripped' binary.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple tvOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible tvOS version for target simulators and devices. If unspecified, uses 'tvos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures for which to build Apple visionOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Comma-separated list of architectures for which to build Apple watchOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible watchOS version for target simulators and devices. If unspecified, uses 'watchos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use XbinaryFDO profile information to optimize compilation. Specify the name of default cross binary profile. When the option is used together with --fdo\_instrument/--fdo\_optimize/--fdo\_profile, those options will always prevail as if xbinary\_fdo is never specified.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If disabled, visibility errors in target dependencies are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Whether to desugar Java 8 bytecode before dexing.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Whether to include supported Java 8 libraries in apps for legacy devices.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Checks the environments each target is compatible with and reports errors if any target has dependencies that don't support the same environments
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable package()s to set the transitive\_visibility attribute to restrict which packages may depend on them.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, enforce that a java\_binary rule can't contain more than one version of the same class file on the classpath. This enforcement can break the build, or can just result in warnings.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If true, checks that a Java target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If enabled, check testonly for prerequisite targets that are output files by looking up the testonly of the generating rule. This matches visibility checking.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When enabled, and with experimental\_one\_version\_enforcement set to a non-NONE value, enforce one version on java\_test targets. This flag can be disabled to improve incremental test performance at the expense of missing potential one version violations.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Unless OFF, checks that a proto\_library target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Unless OFF, checks that a proto\_library target explicitly declares all targets used in 'import public' as exported.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, headers found through system include paths (-isystem) are also required to be declared.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Declares this build's target environment. Must be a label reference to an
`environment` rule. If specified, all top-level targets must be compatible with this
environment.
See also `--platforms`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Options that affect the signing outputs of a build
Implementation to use to sign APKs
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set, and compilation mode is not 'opt', objc apps will include debug entitlements when signing.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If true, disallow sdk\_frameworks and weak\_sdk\_frameworks attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, make the default value true for alwayslink attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
If true, an analysis failure of a rule target results in the target's propagation
of an instance of `AnalysisFailureInfo` containing the error description, instead
of resulting in a build failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Sets the maximum number of transitive dependencies through a rule attribute with
a `for_analysis_testing` configuration transition.
Exceeding this limit will result in a rule error.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Override the default resources amount for tests. The expected format is
`{resource}={value}`. If a single positive number is specified as `{value}`
it will override the default resources for all test sizes. If 4
comma-separated numbers are specified, they will override the resource
amount for respectively the `small`, `medium`, `large`, `enormous` test sizes.
Values can also be `HOST_RAM`/`HOST_CPU`, optionally followed
by `[-|*]{float}` (eg. `memory=HOST_RAM*.1,HOST_RAM*.2,HOST_RAM*.3,HOST_RAM*.4`).
The default test resources specified by this flag are overridden by explicit
resources specified in tags.
*May be used multiple times; values are accumulated.*
Specifies number of times to run each test. If any of those attempts fail for any
reason, the whole test is considered failed. Normally the value specified is
just an integer.
Example: `--runs_per_test=3` will run all tests 3 times.
Alternate syntax: `regex_filter@runs_per_test`. Where `runs_per_test` stands for
an integer value and `regex_filter` stands for a list of include and exclude
regular expression patterns (Also see --instrumentation\_filter).
Example: `--runs_per_test=//foo/.*,-//foo/bar/.*@3` runs all tests in `//foo/` except
those under `//foo/bar` three times. This option can be passed multiple times. The most
recently passed argument that matches takes precedence. If nothing matches,
the test is only run once.
*May be used multiple times; values are accumulated.*
Specifies additional environment variables to be injected into the test runner
environment. Variables can be either specified by `name`, in which
case its value will be read from the Bazel client environment, or by the
`name=value` pair.
Previously set variables can be unset via `=name`.
This option can be used multiple times to specify several variables.
Used only by the 'bazel test' command.
*May be used multiple times; values are accumulated.*
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Override the default test timeout values for test timeouts (in secs). If a single
positive integer value is specified it will override all categories. If 4
comma-separated integers are specified, they will override the timeouts for
`short`, `moderate`, `long` and `eternal` (in that order). In either form, a value of
-1 tells blaze to use its default timeouts for that category.
If true, undeclared test outputs will be archived in a zip file.
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Options that trigger optimizations of the build time
Whether to generate and analyze .d files.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, C++ .d files will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, the dependency (.jdeps) files generated from Java compilations will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, `--trim_test_configuration` will not trim the test configuration for rules
marked testonly=1. This is meant to reduce action conflict issues when non-test
rules depend on `cc_test` rules. No effect if `--trim_test_configuration` is
false.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set, .d files emitted by clang will be used to prune the set of inputs passed into objc compiles.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
When building a target //a:a, process headers in all targets that //a:a depends on (if header processing is enabled for the toolchain).
Tags: [`execution`](#effect_tag_EXECUTION)
When enabled, test-related options will be cleared below the top level of the build. When this flag is active, tests cannot be built as dependencies of non-test rules, but changes to test-related options will not cause non-test rules to be re-analyzed.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Options that affect the verbosity, format or location of logging
Print debug information during toolchain resolution. The flag takes a regex, which is checked against toolchain types and specific targets to see which to debug. Multiple regexes may be separated by commas, and then each regex is checked separately. Note: The output of this flag is very complex and will likely only be useful to experts in toolchain resolution.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, visibility errors include additional diagnostic information.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Sets a shorthand name for a Starlark flag. It takes a single key-value pair in the form
`{key}={value}` as an argument.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Miscellaneous options, not otherwise categorized.
Short form: `-t`
If set to `auto`, Bazel reruns a test if and only if:
* Bazel detects changes in the test or its dependencies,
* The test is marked as `external`,
* Multiple test runs were requested with `--runs_per_test`, or
* The test previously failed.
If set to `yes`, Bazel caches all test results except for tests marked as
`external`. If set to `no`, Bazel does not cache any test results.
If `on_failed` or `on_passed`, then Blaze will cancel concurrently running tests on the first
successful run with that result. This is only useful in combination with
`--runs_per_test_detects_flakes`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel fetches the entire coverage data directory for each test during a coverage run.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, coverage for clang will generate an LCOV report.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables reduced classpaths for Java compilations.
Whether to validate java\_\* sources.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The number of CPUs to reserve for Turbine.
Explicitly specify a dependency to JUnit or Hamcrest in a java\_test instead of accidentally obtaining from the TestRunner's deps. Only works for bazel right now.
The Java launcher used by tools that are executed during a build.
Additional options to pass to javac when building tools that are executed during a build.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM when building tools that are executed during the build. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
If true, exclusive tests will run with sandboxed strategy. Add `local` tag to force
an exclusive test run locally
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel uses an environment with a static value for PATH and does not
inherit `LD_LIBRARY_PATH`. Use `--action_env=ENV_VARIABLE` if you want to
inherit specific environment variables from the client, but note that doing so
can prevent cross-user caching if a shared cache is used.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Causes the Java virtual machine of a java test to wait for a connection from a JDWP-compliant debugger (such as jdb) before starting the test. Implies -test\_output=streamed.
Expands to:
* `--test_arg=--wrapper_script_flag=--debug`
* `--test_output=streamed`
* `--test_strategy=exclusive`
* `--test_timeout=9999`
* `--nocache_test_results`
Generate dependency information (for now, compile-time classpath) per Java target.
Compile ijars directly from source.
The Java language version
The Java launcher to use when building Java binaries. If this flag is set to the empty string, the JDK launcher is used. The "launcher" attribute overrides this flag.
The Java runtime version
Additional options to pass to javac.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
Specifies a binary to use to generate the list of classes that must be in the main dex when compiling legacy multidex.
Specifies a binary to use to do dexing without sharding.
Plugins to use in the build. Currently works with java\_plugin.
*May be used multiple times; values are accumulated.*
Specifies which version of ProGuard to use for code removal when building a Java binary.
The label of the proto-compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether to pass profile\_path to the proto compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
The profile to pass to the proto compiler as profile\_path. If unset, but --proto\_profile is true (the default), infers the path from --fdo\_optimize.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile C++ protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile Java protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile JavaLite protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional options to pass to the protobuf compiler.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, any shard in which at least one run/attempt passes and at least one run/attempt fails gets a FLAKY status.
Absolute path to the shell executable for Bazel to use. If this is unset, but the
`BAZEL_SH` environment variable is set on the first Bazel invocation (that starts
up a Bazel server), Bazel uses that. If neither is set, Bazel uses a hard-coded
default path depending on the operating system it runs on;
* Windows: `c:/msys64/usr/bin/bash.exe`
* FreeBSD and OpenBSD: `/usr/local/bin/bash`
* All others: `/bin/bash`.
Note that using a shell that is not compatible with `bash` may lead
to build failures or runtime failures of the generated binaries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies additional options and arguments that should be passed to the test
executable. Can be used multiple times to specify several arguments.
If multiple tests are executed, each of them will receive identical arguments.
Used only by the `bazel test` command.
*May be used multiple times; values are accumulated.*
Specifies a filter to forward to the test framework. Used to limit the tests run. Note that this does not affect which targets are built.
Forwards fail fast option to the test runner. The test runner should stop execution upon first failure.
Specify strategy for test sharding:
* `explicit` to only use sharding if the `shard_count` `BUILD` attribute is
present.
* `disabled` to never use test sharding.
* `forced=k` to enforce `k` shards for testing regardless of the `shard_count` `BUILD`
attribute.
The Java language version used to execute the tools that are needed during a build
The Java runtime version used to execute tools during the build
If enabled, this option causes Java compilation to use interface jars. This will result in faster incremental compilation, but error messages can be different.
## Help Options
Options that affect the verbosity, format or location of logging
Select the verbosity of the help command.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Short form: `-l`
Show full description of each option, instead of just its name.
Expands to:
* `--help_verbosity=long`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Show only the names of the options, not their types or meanings.
Expands to:
* `--help_verbosity=short`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
## Info Options
Inherits all options from [build](#build).
Options that let the user configure the intended output, affecting its value, as opposed to its existence
If stdout, results are directly printed to the console. If response\_proto, the info command results are packed in response extensions.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Options that affect the verbosity, format or location of logging
Include the "Make" environment in the output.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
## License Options
## Mobile-install Options
Inherits all options from [build](#build).
Options that control build execution
Deprecated no-effect flag. Only skylark mode is still supported.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`deprecated`](#metadata_tag_DEPRECATED)
Options that configure the toolchain used for action execution
adb binary to use for the 'mobile-install' command. If unspecified, the one in the Android SDK specified by the --android\_sdk\_channel command line option (or the default SDK if --android\_sdk\_channel is not specified) is used.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Options that control the output of the command
Whether to do an incremental install. If true, try to avoid unnecessary additional work by reading the state of the device the code is to be installed on and using that information to avoid unnecessary work. If false (the default), always do a full install.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether to use split apks to install and update the application on the device. Works only with devices with Marshmallow or later
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Extra arguments to pass to adb. Usually used to designate a device to install to.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Whether to wait for the debugger before starting the app.
Expands to:
* `--start=DEBUG`
Tags: [`execution`](#effect_tag_EXECUTION)
The adb device serial number. If not specified, the first device will be used.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
How the app should be started after installing it. Set to WARM to preserve and restore application state on incremental installs.
Tags: [`execution`](#effect_tag_EXECUTION)
Whether to start the app after installing it.
Expands to:
* `--start=COLD`
Tags: [`execution`](#effect_tag_EXECUTION)
Options that affect the verbosity, format or location of logging
The verbosity for incremental install. Set to 1 for debug logging.
Tags: [`bazel_monitoring`](#effect_tag_BAZEL_MONITORING)
## Mod Options
Options that control build execution
Whether to make source manifest actions remotable
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Number of parallel threads to use for the loading/analysis phase.Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". "auto" sets a reasonable default based on host resources. Must be at least 1.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Add or remove keys from an action's execution info based on action mnemonic.
Applies only to actions which support execution info. Many common actions
support execution info, e.g. Genrule, CppCompile, Javac, StarlarkAction,
TestRunner. When specifying multiple values, order matters because
many regexes may apply to the same mnemonic.
Syntax: `regex=[+-]key,regex=[+-]key,...`.
Examples:
* `.*=+x,.*=-y,.*=+z` adds `x` and `z` to, and removes `y` from, the execution info for all actions.
* `Genrule=+requires-x` adds `requires-x` to the execution info for all Genrule actions.
* `(?!Genrule).*=-requires-x` removes `requires-x` from the execution info for all non-Genrule actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that configure the toolchain used for action execution
If enabled, `bazel test --run_under=//:runner` builds `//:runner` in the exec
configuration. If disabled, it builds `//:runner` in the target configuration.
Bazel executes tests on exec machines, so the former is more correct. This
doesn't affect `bazel run`, which always builds `--run_under=//foo` in the
target configuration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that control the output of the command
If true, build runfiles symlink forests for all targets. If false, write them only when required by a local action, test or run command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, write runfiles manifests for all targets. If false, omit them. Local tests will fail to run when false.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, native rules add `DefaultInfo.files` of data dependencies to their runfiles,
which matches the recommended behavior for Starlark rules ([runfiles features to avoid](https://bazel.build/extending/rules#runfiles_features_to_avoid)).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, the `{binary}.repo_mapping` file emits a module extension's repo mapping
only once instead of once for each repo generated by the extension that
contributes runfiles.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
List of flags for which the use in `select()` is disabled.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If true, runfiles of targets listed in the srcs attribute are available to targets that consume the filegroup as a data dependency.
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, when artifacts from the same target in multiple configurations are encountered
when constructing runfiles, prefer the version that matches the configuration of the
depending target. Specifically, when a target T depends on a target A in multiple
configurations, either directly or transitively, prefer the runfiles from the
version of A in the configuration that matches the configuration of T. This can happen,
for example, when a target appears in both the tools and data attributes.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Specifies the set of environment variables available to actions with target
configuration. Variables can be either specified by `name`, in which case
the value will be taken from the invocation environment, by the `name=value`
pair which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can be used
multiple times; for options given for the same variable, the latest wins,
options for different variables accumulate.
Note that unless `--incompatible_repo_env_ignores_action_env` is true, all `name=value`
pairs will be available to repository rules.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Allowed values for the `--cpu` flag.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If specified, Bazel will instrument code (using offline instrumentation where
possible) and will collect coverage information during tests. Only targets that
match `--instrumentation_filter` will be affected. Usually this option should
not be specified directly - `bazel coverage` command should be used instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-c`
Specify the mode the binary will be built in. Values: `fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Deprecated: this flag is not used internally by Blaze although there are legacy platform
mappings to allow for backwards compatibility. Do not use this flag, instead use
`--platforms` with an appropriate platform definition.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each `--define` option specifies an assignment for a build variable.
In case of multiple values for a variable, the last one wins.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Enable runfiles symlink tree; By default, it's off on Windows, on on other platforms.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of aspects to be applied to exec-configured targets, regardless of whether or not they are top-level targets. This is an experimental feature and is subject to change.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Use `action_listener` to attach an `extra_action` to
existing build actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If specified, Bazel will also generate collect coverage information for generated files.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Which model to use for where in the output tree rules write their outputs, particularly
for multi-platform / multi-configuration builds. This is highly experimental. See
[GH-6526](https://github.com/bazelbuild/bazel/issues/6526) for details. Starlark actions can opt into path mapping by adding the key
`supports-path-mapping` to the `execution_requirements` dict.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
Please only use this flag as part of a suggested migration or testing strategy. Note
that the heuristic has known deficiencies and it is suggested to migrate to
relying on just `--override_platform_cpu_name`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The given features will be enabled or disabled by default for targets built in the target configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
See also `--host_features`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to actions with execution
configurations. Variables can be either specified by `name`, in which case the
value will be taken from the invocation environment, by the `name=value` pair
which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can
be used multiple times; for options given for the same variable, the latest
wins, options for different variables accumulate.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Specify the mode the tools used during the build will be built in. Values:
`fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
The host CPU.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the exec configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When enabled, an exec groups is automatically created for each toolchain used by a rule.
For this to work rule needs to specify `toolchain` parameter on its actions. For
more information, see [GH-17134](https://github.com/bazelbuild/bazel/issues/17134).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, the genfiles directory is folded into the bin directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If specified, the value of the cpu constraint (`@platforms//cpu:cpu`) of
the target platform is used to set the `$(TARGET_CPU)` make variable.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When coverage is enabled, specifies whether to consider instrumenting test rules.
When set, test rules included by `--instrumentation_filter` are instrumented.
Otherwise, test rules are always excluded from coverage instrumentation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When coverage is enabled, only rules with names included by the
specified regex-based filter will be instrumented. Rules prefixed
with '-' are excluded instead. Note that only non-test rules are
instrumented unless `--instrument_test_targets` is enabled.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each entry should be of the form `label=value` where label refers to a platform and values
is the desired shortname to override the platform's CPU name in `$(TARGET_CPU)`
make variable and output path. Only used when `--incompatible_target_cpu_from_platform` or
`--incompatible_bep_cpu_from_platform` is true. Has highest naming priority.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a suffix to be added to the configuration directory.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Prefix to insert before the executables for the `test` and `run` commands.
If the value is `foo -bar`, and the execution command line is `test_binary -baz`,
then the final command line is `foo -bar test_binary -baz`.
This can also be a label to an executable target. Some examples are:
* `valgrind`
* `strace`
* `strace -c`
* `valgrind --quiet --num-callers=20`
* `//package:target`
* `//package:target --options`
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Stamp binaries with the date, username, hostname, workspace information, etc.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If disabled, visibility errors in target dependencies are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Checks the environments each target is compatible with and reports errors if any target has dependencies that don't support the same environments
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable package()s to set the transitive\_visibility attribute to restrict which packages may depend on them.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, check testonly for prerequisite targets that are output files by looking up the testonly of the generating rule. This matches visibility checking.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Declares this build's target environment. Must be a label reference to an
`environment` rule. If specified, all top-level targets must be compatible with this
environment.
See also `--platforms`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If incompatible\_enforce\_config\_setting\_visibility=false, this is a noop. Else, if this flag is false, any config\_setting without an explicit visibility attribute is //visibility:public. If this flag is true, config\_setting follows the same visibility logic as all other rules. See [https://github.com/bazelbuild/bazel/issues/12933](https://github.com/bazelbuild/bazel/issues/12933).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, enforce config\_setting visibility restrictions. If false, every config\_setting is visible to every target. See [https://github.com/bazelbuild/bazel/issues/12932](https://github.com/bazelbuild/bazel/issues/12932).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
If true, an analysis failure of a rule target results in the target's propagation
of an instance of `AnalysisFailureInfo` containing the error description, instead
of resulting in a build failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Sets the maximum number of transitive dependencies through a rule attribute with
a `for_analysis_testing` configuration transition.
Exceeding this limit will result in a rule error.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options relating to the output and semantics of the `mod` subcommand
For `mod show_repo`: display all repos in the entire workspace.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
For `mod show_repo`: display all repos visible to the chosen base module, under their apparent names.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Specify a module relative to which the specified target repos will be interpreted.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Chooses the character set to use for the tree. Only affects text output. Valid values
are `utf8` or `ascii`. Default is `utf8`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Points out dependency cycles inside the displayed tree.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Maximum display depth of the dependency tree. A depth of 1 displays the direct
dependencies, for example. For `tree`, `path` and `all_paths` it defaults to
`Integer.MAX_VALUE`, while for `deps` and `explain` it defaults to 1 (only displays
direct deps of the root besides the target leaves and their parents).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Only display the usages of these module extensions and the repos generated by them if their respective flags are set. If set, the result graph will only include paths that contain modules using the specified extensions. An empty list disables the filter, effectively specifying all possible extensions.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Specify how much detail about extension usages to include in the query result.
* `hidden` will not show any extension information.
* `usages` will only show the extensions names.
* `repos` will also include repos imported with `use_repo`.
* `all` will also show the other repositories generated by extensions.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Specify modules whose extension usages will be displayed in the show\_extension query.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The module(s) starting from which the dependency graph query will be displayed. Check
each query’s description for the exact semantics. Defaults to ``.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Include built-in modules in the dependency graph. Disabled by default because it is quite noisy.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The queries will also take into account and display the unused modules, which are not
present in the module resolution graph after selection (due to the
Minimal-Version Selection or override rules). This can have different effects for
each of the query types i.e. include new paths in the `all_paths` command, or extra
dependants in the `explain` command.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The format in which the query results should be printed. Allowed values for query are:
`text`, `json`, `graph`.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The queries will also display the reason why modules were resolved to their current version (if changed). Defaults to true only for the explain query.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Options that affect the verbosity, format or location of logging
If enabled, visibility errors include additional diagnostic information.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Sets a shorthand name for a Starlark flag. It takes a single key-value pair in the form
`{key}={value}` as an argument.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Miscellaneous options, not otherwise categorized.
A comma-separated list of names of packages which the build system will consider non-existent, even if they are visible somewhere on the package path.
Use this option when deleting a subpackage 'x/y' of an existing package 'x'. For example, after deleting x/y/BUILD in your client, the build system may complain if it encounters a label '//x:y/z' if that is still provided by another package\_path entry. Specifying --deleted\_packages x/y avoids this problem.
*May be used multiple times; values are accumulated.*
Allows the command to fetch external dependencies. If set to false, the command will utilize any cached version of the dependency, and if none exists, the command will result in failure.
A colon-separated list of where to look for packages. Elements beginning with '%workspace%' are relative to the enclosing workspace. If omitted or empty, the default is the output of 'bazel info default-package-path'.
If enabled, causes Bazel to print "Loading package:" messages.
## Print\_action Options
Inherits all options from [build](#build).
Miscellaneous options, not otherwise categorized.
Lists which mnemonics to filter print\_action data by, no filtering takes place when left empty.
*May be used multiple times; values are accumulated.*
## Query Options
Options that control build execution
Whether to make source manifest actions remotable
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Short form: `-k`
Continue as much as possible after an error. While the target that failed and those that depend on it cannot be analyzed, other prerequisites of these targets can be.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Number of parallel threads to use for the loading/analysis phase.Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". "auto" sets a reasonable default based on host resources. Must be at least 1.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
Add or remove keys from an action's execution info based on action mnemonic.
Applies only to actions which support execution info. Many common actions
support execution info, e.g. Genrule, CppCompile, Javac, StarlarkAction,
TestRunner. When specifying multiple values, order matters because
many regexes may apply to the same mnemonic.
Syntax: `regex=[+-]key,regex=[+-]key,...`.
Examples:
* `.*=+x,.*=-y,.*=+z` adds `x` and `z` to, and removes `y` from, the execution info for all actions.
* `Genrule=+requires-x` adds `requires-x` to the execution info for all Genrule actions.
* `(?!Genrule).*=-requires-x` removes `requires-x` from the execution info for all non-Genrule actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that configure the toolchain used for action execution
If enabled, `bazel test --run_under=//:runner` builds `//:runner` in the exec
configuration. If disabled, it builds `//:runner` in the target configuration.
Bazel executes tests on exec machines, so the former is more correct. This
doesn't affect `bazel run`, which always builds `--run_under=//foo` in the
target configuration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that control the output of the command
If true, build runfiles symlink forests for all targets. If false, write them only when required by a local action, test or run command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, write runfiles manifests for all targets. If false, omit them. Local tests will fail to run when false.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, native rules add `DefaultInfo.files` of data dependencies to their runfiles,
which matches the recommended behavior for Starlark rules ([runfiles features to avoid](https://bazel.build/extending/rules#runfiles_features_to_avoid)).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, the `{binary}.repo_mapping` file emits a module extension's repo mapping
only once instead of once for each repo generated by the extension that
contributes runfiles.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
List of flags for which the use in `select()` is disabled.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If true, runfiles of targets listed in the srcs attribute are available to targets that consume the filegroup as a data dependency.
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, when artifacts from the same target in multiple configurations are encountered
when constructing runfiles, prefer the version that matches the configuration of the
depending target. Specifically, when a target T depends on a target A in multiple
configurations, either directly or transitively, prefer the runfiles from the
version of A in the configuration that matches the configuration of T. This can happen,
for example, when a target appears in both the tools and data attributes.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Specifies the set of environment variables available to actions with target
configuration. Variables can be either specified by `name`, in which case
the value will be taken from the invocation environment, by the `name=value`
pair which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can be used
multiple times; for options given for the same variable, the latest wins,
options for different variables accumulate.
Note that unless `--incompatible_repo_env_ignores_action_env` is true, all `name=value`
pairs will be available to repository rules.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Allowed values for the `--cpu` flag.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If specified, Bazel will instrument code (using offline instrumentation where
possible) and will collect coverage information during tests. Only targets that
match `--instrumentation_filter` will be affected. Usually this option should
not be specified directly - `bazel coverage` command should be used instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-c`
Specify the mode the binary will be built in. Values: `fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Deprecated: this flag is not used internally by Blaze although there are legacy platform
mappings to allow for backwards compatibility. Do not use this flag, instead use
`--platforms` with an appropriate platform definition.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each `--define` option specifies an assignment for a build variable.
In case of multiple values for a variable, the last one wins.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Enable runfiles symlink tree; By default, it's off on Windows, on on other platforms.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of aspects to be applied to exec-configured targets, regardless of whether or not they are top-level targets. This is an experimental feature and is subject to change.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Use `action_listener` to attach an `extra_action` to
existing build actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If specified, Bazel will also generate collect coverage information for generated files.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Which model to use for where in the output tree rules write their outputs, particularly
for multi-platform / multi-configuration builds. This is highly experimental. See
[GH-6526](https://github.com/bazelbuild/bazel/issues/6526) for details. Starlark actions can opt into path mapping by adding the key
`supports-path-mapping` to the `execution_requirements` dict.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
Please only use this flag as part of a suggested migration or testing strategy. Note
that the heuristic has known deficiencies and it is suggested to migrate to
relying on just `--override_platform_cpu_name`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The given features will be enabled or disabled by default for targets built in the target configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
See also `--host_features`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to actions with execution
configurations. Variables can be either specified by `name`, in which case the
value will be taken from the invocation environment, by the `name=value` pair
which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can
be used multiple times; for options given for the same variable, the latest
wins, options for different variables accumulate.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Specify the mode the tools used during the build will be built in. Values:
`fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
The host CPU.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the exec configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When enabled, an exec groups is automatically created for each toolchain used by a rule.
For this to work rule needs to specify `toolchain` parameter on its actions. For
more information, see [GH-17134](https://github.com/bazelbuild/bazel/issues/17134).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, the genfiles directory is folded into the bin directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If specified, the value of the cpu constraint (`@platforms//cpu:cpu`) of
the target platform is used to set the `$(TARGET_CPU)` make variable.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When coverage is enabled, specifies whether to consider instrumenting test rules.
When set, test rules included by `--instrumentation_filter` are instrumented.
Otherwise, test rules are always excluded from coverage instrumentation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When coverage is enabled, only rules with names included by the
specified regex-based filter will be instrumented. Rules prefixed
with '-' are excluded instead. Note that only non-test rules are
instrumented unless `--instrument_test_targets` is enabled.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each entry should be of the form `label=value` where label refers to a platform and values
is the desired shortname to override the platform's CPU name in `$(TARGET_CPU)`
make variable and output path. Only used when `--incompatible_target_cpu_from_platform` or
`--incompatible_bep_cpu_from_platform` is true. Has highest naming priority.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a suffix to be added to the configuration directory.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Prefix to insert before the executables for the `test` and `run` commands.
If the value is `foo -bar`, and the execution command line is `test_binary -baz`,
then the final command line is `foo -bar test_binary -baz`.
This can also be a label to an executable target. Some examples are:
* `valgrind`
* `strace`
* `strace -c`
* `valgrind --quiet --num-callers=20`
* `//package:target`
* `//package:target --options`
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Stamp binaries with the date, username, hostname, workspace information, etc.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If disabled, visibility errors in target dependencies are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Checks the environments each target is compatible with and reports errors if any target has dependencies that don't support the same environments
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable package()s to set the transitive\_visibility attribute to restrict which packages may depend on them.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, check testonly for prerequisite targets that are output files by looking up the testonly of the generating rule. This matches visibility checking.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Declares this build's target environment. Must be a label reference to an
`environment` rule. If specified, all top-level targets must be compatible with this
environment.
See also `--platforms`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If incompatible\_enforce\_config\_setting\_visibility=false, this is a noop. Else, if this flag is false, any config\_setting without an explicit visibility attribute is //visibility:public. If this flag is true, config\_setting follows the same visibility logic as all other rules. See [https://github.com/bazelbuild/bazel/issues/12933](https://github.com/bazelbuild/bazel/issues/12933).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, enforce config\_setting visibility restrictions. If false, every config\_setting is visible to every target. See [https://github.com/bazelbuild/bazel/issues/12932](https://github.com/bazelbuild/bazel/issues/12932).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
If true, an analysis failure of a rule target results in the target's propagation
of an instance of `AnalysisFailureInfo` containing the error description, instead
of resulting in a build failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Sets the maximum number of transitive dependencies through a rule attribute with
a `for_analysis_testing` configuration transition.
Exceeding this limit will result in a rule error.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options relating to query output and semantics
How to resolve aspect dependencies when the output format is one of \{xml,proto,record}. 'off' means no aspect dependencies are resolved, 'conservative' (the default) means all declared aspect dependencies are added regardless of whether they are given the rule class of direct dependencies, 'precise' means that only those aspects are added that are possibly active given the rule class of the direct dependencies. Note that precise mode requires loading other packages to evaluate a single target thus making it slower than the other modes. Also note that even precise mode is not completely precise: the decision whether to compute an aspect is decided in the analysis phase, which is not run during 'bazel query'.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If enabled, every query command emits labels as if by the Starlark `str` function applied to a `Label` instance. This is useful for tools that need to match the output of different query commands and/or labels emitted by rules. If not enabled, output formatters are free to emit apparent repository names (relative to the main repository) instead to make the output more readable.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
aquery, cquery: whether to include aspect-generated actions in the output. query: no-op (aspects are always followed).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, uses a Query implementation that does not make a copy of the graph. The new implementation only supports --order\_output=no, as well as only a subset of output formatters.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If true, --output=streamed\_proto serializes targets in parallel while preserving output order. Has no effect when --proto:rule\_classes is enabled.
Tags: [`host_machine_resource_optimizations`](#effect_tag_HOST_MACHINE_RESOURCE_OPTIMIZATIONS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The maximum number of condition labels to show. -1 means no truncation and 0 means no annotation. This option is only applicable to --output=graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, then the graph will be emitted 'factored', i.e. topologically-equivalent nodes will be merged together and their labels concatenated. This option is only applicable to --output=graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The maximum length of the label string for a graph node in the output. Longer labels will be truncated; -1 means no truncation. This option is only applicable to --output=graph.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, implicit dependencies will be included in the dependency graph over which the query operates. An implicit dependency is one that is not explicitly specified in the BUILD file but added by bazel. For cquery, this option controls filtering resolved toolchains.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
aquery, cquery: whether to include aspect-generated actions in the output. query: no-op (aspects are always followed).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, `blaze query --output=build` will output `package_group` targets.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, when outputting package\_group's `packages` attribute, the leading `//` will not be omitted.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If set and --universe\_scope is unset, then a value of --universe\_scope will be inferred as the list of unique target patterns in the query expression. Note that the --universe\_scope value inferred for a query expression that uses universe-scoped functions (e.g.`allrdeps`) may not be what you want, so you should use this option only if you know what you are doing. See [https://bazel.build/reference/query#sky-query](https://bazel.build/reference/query#sky-query) for details and examples. If --universe\_scope is set, then this option's value is ignored. Note: this option applies only to `query` (i.e. not `cquery`).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether each format is terminated with \0 instead of newline.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, deps from "nodep" attributes will be included in the dependency graph over which the query operates. A common example of a "nodep" attribute is "visibility". Run and parse the output of `info build-language` to learn about all the "nodep" attributes in the build language.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Output the results in dependency-ordered (default) or unordered fashion. The unordered output is faster but only supported when --output is not minrank, maxrank, or graph.
Expands to:
* `--order_output=no`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether each format is terminated with \0 instead of newline.
Expands to:
* `--line_terminator_null=true`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Output the results unordered (no), dependency-ordered (deps), or fully ordered (full). The default is 'auto', meaning that results are output either dependency-ordered or fully ordered, depending on the output formatter (dependency-ordered for proto, minrank, maxrank, and graph, fully ordered for all others). When output is fully ordered, nodes are printed in a fully deterministic (total) order. First, all nodes are sorted alphabetically. Then, each node in the list is used as the start of a post-order depth-first search in which outgoing edges to unvisited nodes are traversed in alphabetical order of the successor nodes. Finally, nodes are printed in the reverse of the order in which they were visited.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Output the results in dependency-ordered (default) or unordered fashion. The unordered output is faster but only supported when --output is not minrank, maxrank, or graph.
Expands to:
* `--order_output=auto`
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
The format in which the query results should be printed. Allowed values for query are: build, graph, streamed\_jsonproto, label, label\_kind, location, maxrank, minrank, package, proto, streamed\_proto, xml.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
When displaying rule kind, whether to display the short rule name, or the full name for Starlark rules.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
When specified, query results will be written directly to this file, and nothing will be printed to Bazel's standard output stream (stdout). In benchmarks, this is generally faster than `bazel query > file`.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, attributes whose value is not explicitly specified in the BUILD file are included; otherwise they are omitted. This option is applicable to --output=proto
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the definition\_stack proto field, which records for each rule instance the Starlark call stack at the moment the rule's class was defined.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, configurable attributes created by select() are flattened. For list types the flattened representation is a list containing each value of the select map exactly once. Scalar types are flattened to null.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
Populate the source\_aspect\_name proto field of each Attribute with the source aspect that the attribute came from (empty string if it did not).
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Use the starlark environment in the value of the generated \$internal\_attr\_hash attribute. This ensures that the starlark rule definition (and its transitive imports) are part of this identifier.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether or not to calculate and populate the \$internal\_attr\_hash attribute.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the instantiation call stack of each rule. Note that this requires the stack to be present
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether to output location information in proto output at all.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Comma separated list of attributes to include in output. Defaults to all attributes. Set to empty string to not output any attribute. This option is applicable to --output=proto.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Populate the rule\_class\_key field of each rule; and for the first rule with a given rule\_class\_key, also populate its rule\_class\_info proto field. The rule\_class\_key field uniquely identifies a rule class, and the rule\_class\_info field is a Stardoc-format rule class API definition.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Whether or not to populate the rule\_input and rule\_output fields.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If set, query will read the query from the file named here, rather than on the command line. It is an error to specify a file here as well as a command-line query.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
If true, the location of BUILD files in xml and proto outputs will be relative. By default, the location output is an absolute path and will not be consistent across machines. You can set this option to true to have a consistent result across machines.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, the tests() expression gives an error if it encounters a test\_suite containing non-test targets.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Query: If disabled, dependencies on 'exec configuration' will not be included in the dependency graph over which the query operates. An 'exec configuration' dependency edge, such as the one from any 'proto\_library' rule to the Protocol Compiler, usually points to a tool executed during the build rather than a part of the same 'target' program.
Cquery: If disabled, filters out all configured targets which cross an execution transition from the top-level target that discovered this configured target. That means if the top-level target is in the target configuration, only configured targets also in the target configuration will be returned. If the top-level target is in the exec configuration, only exec configured targets will be returned. This option will NOT exclude resolved toolchains.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
A comma-separated set of target patterns (additive and subtractive). The query may be performed in the universe defined by the transitive closure of the specified targets. This option is used for the query and cquery commands.
For cquery, the input to this option is the targets all answers are built under and so this option may affect configurations and transitions. If this option is not specified, the top-level targets are assumed to be the targets parsed from the query expression. Note: For cquery, not specifying this option may cause the build to break if targets parsed from the query expression are not buildable with top-level options.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If true, rule attributes whose value is not explicitly specified in the BUILD file are printed; otherwise they are omitted.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If true, XML output contains line numbers. Disabling this option may make diffs easier to read. This option is only applicable to --output=xml.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
Options that affect the verbosity, format or location of logging
If enabled, visibility errors include additional diagnostic information.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Sets a shorthand name for a Starlark flag. It takes a single key-value pair in the form
`{key}={value}` as an argument.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Miscellaneous options, not otherwise categorized.
A comma-separated list of names of packages which the build system will consider non-existent, even if they are visible somewhere on the package path.
Use this option when deleting a subpackage 'x/y' of an existing package 'x'. For example, after deleting x/y/BUILD in your client, the build system may complain if it encounters a label '//x:y/z' if that is still provided by another package\_path entry. Specifying --deleted\_packages x/y avoids this problem.
*May be used multiple times; values are accumulated.*
Allows the command to fetch external dependencies. If set to false, the command will utilize any cached version of the dependency, and if none exists, the command will result in failure.
A colon-separated list of where to look for packages. Elements beginning with '%workspace%' are relative to the enclosing workspace. If omitted or empty, the default is the output of 'bazel info default-package-path'.
If enabled, causes Bazel to print "Loading package:" messages.
## Run Options
Inherits all options from [build](#build).
Options that appear before the command and are parsed by the client
If true, includes paths to replace in ExecRequest to make the resulting paths portable.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If false, skip running the command line constructed for the built target. Note that this flag is ignored for all --script\_path builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to the target to run. Variables can be either specified by name, in which case the value will be taken from the invocation environment, by the \name=value\ pair which sets the value independent of the invocation environment, or by \=name\, which unsets the variable of that name. This option can be used multiple times; for options given for the same variable, the latest wins, options for different variables accumulate. Note that the executed target will generally see the full environment of the host except for those variables that have been explicitly unset.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, runs the target in the current working directory instead of the runfile tree.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
If set, write a shell script to the given file which invokes the target. If this option is set, the target is not run from bazel. Use 'bazel run --script\_path=foo //foo && ./foo' to invoke target '//foo'.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
Options that affect the verbosity, format or location of logging
Specifies whether the arguments passed to the runnable target will be omitted from the output for privacy reasons. If set to true, the output will not contain the arguments passed to the target. If set to false, the output will contain the arguments passed to the target.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
## Shutdown Options
Options that control the output of the command
Iff non-zero, then shutdown will only shut down the server if the total memory (in MB) consumed by the JVM exceeds this value.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
## Test Options
Inherits all options from [build](#build).
Options that affect the verbosity, format or location of logging
If true, when printing the path to a test log, use relative path that makes use of the 'testlogs' convenience symlink. N.B. - A subsequent 'build'/'test'/etc invocation with a different configuration can cause the target of this symlink to change, making the path printed previously no longer useful.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, print additional warnings when the actual test execution time does not match the timeout defined by the test (whether implied or explicit).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, print additional information (timing, number of failed runs, etc) in the test summary.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
## Vendor Options
Inherits all options from [test](#test).
Options that control build execution
Short form: `-k`
Continue as much as possible after an error. While the target that failed and those that depend on it cannot be analyzed, other prerequisites of these targets can be.
Tags: [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Number of parallel threads to use for the loading/analysis phase.Takes an integer, or a keyword ("auto", "HOST\_CPUS", "HOST\_RAM"), optionally followed by an operation (\[-|*]\) eg. "auto", "HOST\_CPUS*.5". "auto" sets a reasonable default based on host resources. Must be at least 1.
Tags: [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If incompatible\_enforce\_config\_setting\_visibility=false, this is a noop. Else, if this flag is false, any config\_setting without an explicit visibility attribute is //visibility:public. If this flag is true, config\_setting follows the same visibility logic as all other rules. See [https://github.com/bazelbuild/bazel/issues/12933](https://github.com/bazelbuild/bazel/issues/12933).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, enforce config\_setting visibility restrictions. If false, every config\_setting is visible to every target. See [https://github.com/bazelbuild/bazel/issues/12932](https://github.com/bazelbuild/bazel/issues/12932).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options relating to Bzlmod output and semantics
Also vendors the repositories required to update the lockfile, e.g. with `bazel mod tidy`, while fetching is disabled. These include the repositories hosting all module
extensions in the dependency graph, even those only used by dependencies, as well as
buildozer. Can be combined with target patterns, but not with `--repo`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Only vendors the specified repository, which can be either `@apparent_repo_name` or
`@@canonical_repo_name`. This option can be set multiple times.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Miscellaneous options, not otherwise categorized.
A comma-separated list of names of packages which the build system will consider non-existent, even if they are visible somewhere on the package path.
Use this option when deleting a subpackage 'x/y' of an existing package 'x'. For example, after deleting x/y/BUILD in your client, the build system may complain if it encounters a label '//x:y/z' if that is still provided by another package\_path entry. Specifying --deleted\_packages x/y avoids this problem.
*May be used multiple times; values are accumulated.*
Allows the command to fetch external dependencies. If set to false, the command will utilize any cached version of the dependency, and if none exists, the command will result in failure.
A colon-separated list of where to look for packages. Elements beginning with '%workspace%' are relative to the enclosing workspace. If omitted or empty, the default is the output of 'bazel info default-package-path'.
If enabled, causes Bazel to print "Loading package:" messages.
Options that control build execution
Whether to make source manifest actions remotable
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel will run coverage postprocessing for test in a new spawn.
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Add or remove keys from an action's execution info based on action mnemonic.
Applies only to actions which support execution info. Many common actions
support execution info, e.g. Genrule, CppCompile, Javac, StarlarkAction,
TestRunner. When specifying multiple values, order matters because
many regexes may apply to the same mnemonic.
Syntax: `regex=[+-]key,regex=[+-]key,...`.
Examples:
* `.*=+x,.*=-y,.*=+z` adds `x` and `z` to, and removes `y` from, the execution info for all actions.
* `Genrule=+requires-x` adds `requires-x` to the execution info for all Genrule actions.
* `(?!Genrule).*=-requires-x` removes `requires-x` from the execution info for all non-Genrule actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that configure the toolchain used for action execution
Sets the platforms that android\_binary targets use. If multiple platforms are specified, then the binary is a fat APKs, which contains native binaries for each specified target platform.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Specifies a suffix to be added to the configuration directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The C++ compiler to use for compiling the target.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION)
Location of the binary that is used to postprocess raw coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:lcov_merger`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of the binary that is used to generate coverage reports. This must
be a binary target. Defaults to `@bazel_tools//tools/test:coverage_report_generator`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Location of support files that are required on the inputs of every test action
that collects code coverage. Defaults to `//tools/test:coverage_support`.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies a custom malloc implementation. This setting overrides malloc attributes in build rules.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, add a "requires-xcode:\{version}" execution requirement to every Xcode action. If the Xcode version has a hyphenated label, also add a "requires-xcode-label:\{version\_label}" execution requirement.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use the most recent Xcode that is available both locally and remotely. If false, or if there are no mutual available versions, use the local Xcode version selected via xcode-select.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
The platforms that are available as execution platforms to run actions.
Platforms can be specified by exact target, or as a target pattern.
These platforms will be considered before those declared in the `WORKSPACE` file by
`register_execution_platforms()`. This option may only be set once; later
instances will override earlier flag settings.
Tags: [`execution`](#effect_tag_EXECUTION)
The toolchain rules to be considered during toolchain resolution.
Toolchains can be specified by exact target, or as a target pattern.
These toolchains will be considered before those declared in the `WORKSPACE` file
by `register_toolchains()`.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
A label to a checked-in libc library. The default value is selected by the crosstool toolchain, and you almost never need to override it.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If specified, this setting overrides the libc top-level directory (--grte\_top) for the exec configuration.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The label of a platform rule that describes the host system.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If enabled, `bazel test --run_under=//:runner` builds `//:runner` in the exec
configuration. If disabled, it builds `//:runner` in the target configuration.
Bazel executes tests on exec machines, so the former is more correct. This
doesn't affect `bazel run`, which always builds `--run_under=//foo` in the
target configuration.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Whether to emit a strip action as part of objc linking.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not enable 'host' and 'nonhost' features in the c++ toolchain (see [https://github.com/bazelbuild/bazel/issues/7407](https://github.com/bazelbuild/bazel/issues/7407) for more information).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel will not link library dependencies as whole archive by default (see [https://github.com/bazelbuild/bazel/issues/7362](https://github.com/bazelbuild/bazel/issues/7362) for migration instructions).
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, strip action for executables will use flag -x, which does not break dynamic symbol resolution.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Use interface shared objects if supported by the toolchain. All ELF toolchains currently support this setting.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The minimum OS version which your compilation targets.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The location of a mapping file that describes which platform to use if none is set or
which flags to set when a platform already exists. Must be relative to the main
workspace root. Defaults to `platform_mappings` (a file directly under the
workspace root).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
The labels of the platform rules describing the target platforms for the current command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, uses Xcode of the given version for relevant build actions. If unspecified, uses the executor default version of Xcode.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
The label of the xcode\_config rule to be used for selecting the Xcode version in the build configuration.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Options that control the output of the command
Whether to generate debug symbol(.dSYM) file(s).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, build runfiles symlink forests for all targets. If false, write them only when required by a local action, test or run command.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, write runfiles manifests for all targets. If false, omit them. Local tests will fail to run when false.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, when building C++ tests statically and with fission the .dwp file for the test binary will be automatically built as well.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the suffixes of header files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Sets the suffixes of source files that a cc\_proto\_library creates.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Pass the --include\_source\_info flag when building a proto\_library. This results in vastly larger descriptors that include information about the original location of each decl in the source file as well as surrounding comments.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Save the state of enabled and requested feautres as an output of compilation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Specifies which compilation modes use fission for C++ compilations and links. May be any combination of \{'fastbuild', 'dbg', 'opt'} or the special values 'yes' to enable all modes and 'no' to disable all modes.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, native rules add `DefaultInfo.files` of data dependencies to their runfiles,
which matches the recommended behavior for Starlark rules ([runfiles features to avoid](https://bazel.build/extending/rules#runfiles_features_to_avoid)).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If enabled, the `{binary}.repo_mapping` file emits a module extension's repo mapping
only once instead of once for each repo generated by the extension that
contributes runfiles.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
List of flags for which the use in `select()` is disabled.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
If true, runfiles of targets listed in the srcs attribute are available to targets that consume the filegroup as a data dependency.
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, when artifacts from the same target in multiple configurations are encountered
when constructing runfiles, prefer the version that matches the configuration of the
depending target. Specifically, when a target T depends on a target A in multiple
configurations, either directly or transitively, prefer the runfiles from the
version of A in the configuration that matches the configuration of T. This can happen,
for example, when a target appears in both the tools and data attributes.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Specifies whether to generate a linkmap file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, temporary outputs from gcc will be saved. These include .s files (assembler code), .i files (preprocessed C) and .ii files (preprocessed C++).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that let the user configure the intended output, affecting its value, as opposed to its existence
Specifies the set of environment variables available to actions with target
configuration. Variables can be either specified by `name`, in which case
the value will be taken from the invocation environment, by the `name=value`
pair which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can be used
multiple times; for options given for the same variable, the latest wins,
options for different variables accumulate.
Note that unless `--incompatible_repo_env_ignores_action_env` is true, all `name=value`
pairs will be available to repository rules.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Allowed values for the `--cpu` flag.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Sets the order of manifests passed to the manifest merger for Android binaries. ALPHABETICAL means manifests are sorted by path relative to the execroot. ALPHABETICAL\_BY\_CONFIGURATION means manifests are sorted by paths relative to the configuration directory within the output directory. DEPENDENCY means manifests are ordered with each library's manifest coming before the manifests of its dependencies.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`execution`](#effect_tag_EXECUTION)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If specified, Bazel will instrument code (using offline instrumentation where
possible) and will collect coverage information during tests. Only targets that
match `--instrumentation_filter` will be affected. Usually this option should
not be specified directly - `bazel coverage` command should be used instead.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Short form: `-c`
Specify the mode the binary will be built in. Values: `fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to gcc when compiling C source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to gcc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Deprecated: this flag is not used internally by Blaze although there are legacy platform
mappings to allow for backwards compatibility. Do not use this flag, instead use
`--platforms` with an appropriate platform definition.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use CSFDO profile information to optimize compilation. Specify the absolute path name of the zip file containing the profile file, a raw or an indexed LLVM profile file.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Generate binaries with context sensitive FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The cs\_fdo\_profile representing the context sensitive profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to gcc when compiling C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Each `--define` option specifies an assignment for a build variable.
In case of multiple values for a variable, the last one wins.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Determines whether C++ binaries will be linked dynamically. 'default' means Bazel will choose whether to link dynamically. 'fully' means all libraries will be linked dynamically. 'off' means that all libraries will be linked in mostly static mode, the exception being dynamically linked system libraries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for propeller optimize will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If set, any use of absolute paths for FDO will raise an error.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Enable runfiles symlink tree; By default, it's off on Windows, on on other platforms.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of aspects to be applied to exec-configured targets, regardless of whether or not they are top-level targets. This is an experimental feature and is subject to change.
*May be used multiple times; values are accumulated.*
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Deprecated in favor of aspects. Use `action_listener` to attach an `extra_action` to
existing build actions.
*May be used multiple times; values are accumulated.*
Tags: [`execution`](#effect_tag_EXECUTION), [`experimental`](#metadata_tag_EXPERIMENTAL)
Compress Java resources in APKs
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables resource shrinking for android\_binary APKs that use ProGuard.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If specified, Bazel will also generate collect coverage information for generated files.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, use libunwind for stack unwinding, and compile with -fomit-frame-pointer and -fasynchronous-unwind-tables.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Which model to use for where in the output tree rules write their outputs, particularly
for multi-platform / multi-configuration builds. This is highly experimental. See
[GH-6526](https://github.com/bazelbuild/bazel/issues/6526) for details. Starlark actions can opt into path mapping by adding the key
`supports-path-mapping` to the `execution_requirements` dict.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`bazel_internal_configuration`](#effect_tag_BAZEL_INTERNAL_CONFIGURATION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
If specified, Bazel will generate llvm-cov coverage map information rather than gcov when collect\_code\_coverage is enabled.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Please only use this flag as part of a suggested migration or testing strategy. Note
that the heuristic has known deficiencies and it is suggested to migrate to
relying on just `--override_platform_cpu_name`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Generate binaries with FDO instrumentation. With Clang/LLVM compiler, it also accepts the directory name under which the raw profile file(s) will be dumped at runtime.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use FDO profile information to optimize compilation. Specify the name of a zip file containing a .gcda file tree, an afdo file containing an auto profile, or an LLVM profile file. This flag also accepts files specified as labels (e.g. `//foo/bar:file.afdo` - you may need to add an `exports_files` directive to the corresponding package) and labels pointing to `fdo_profile` targets. This flag will be superseded by the `fdo_profile` rule.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Use cache prefetch hints.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The fdo\_profile representing the profile to be used for optimization.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the target configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
See also `--host_features`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If enabled, all C++ compilations produce position-independent code ("-fPIC"), links prefer PIC pre-built libraries over non-PIC libraries, and links produce position-independent executables ("-pie").
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies the set of environment variables available to actions with execution
configurations. Variables can be either specified by `name`, in which case the
value will be taken from the invocation environment, by the `name=value` pair
which sets the value independent of the invocation environment, or by
`=name`, which unsets the variable of that name. This option can
be used multiple times; for options given for the same variable, the latest
wins, options for different variables accumulate.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Specify the mode the tools used during the build will be built in. Values:
`fastbuild`, `dbg`, `opt`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional option to pass to the C compiler when compiling C (but not C++) source files in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to the C compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The host CPU.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to C++ compiler for tools built in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
The given features will be enabled or disabled by default for targets built in the exec configuration.
Specifying `-{feature}` will disable the feature. Negative features always override positive ones.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to linker when linking tools in the exec configurations.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible macOS version for host targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Additional options to selectively pass to the C/C++ compiler when compiling certain files in the exec configurations. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --host\_per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When enabled, an exec groups is automatically created for each toolchain used by a rule.
For this to work rule needs to specify `toolchain` parameter on its actions. For
more information, see [GH-17134](https://github.com/bazelbuild/bazel/issues/17134).
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, the genfiles directory is folded into the bin directory.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If specified, the value of the cpu constraint (`@platforms//cpu:cpu`) of
the target platform is used to set the `$(TARGET_CPU)` make variable.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When coverage is enabled, specifies whether to consider instrumenting test rules.
When set, test rules included by `--instrumentation_filter` are instrumented.
Otherwise, test rules are always excluded from coverage instrumentation.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
When coverage is enabled, only rules with names included by the
specified regex-based filter will be instrumented. Rules prefixed
with '-' are excluded instead. Note that only non-test rules are
instrumented unless `--instrument_test_targets` is enabled.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Minimum compatible iOS version for target simulators and devices. If unspecified, uses 'ios\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures to build an ios\_application with. The result is a universal binary containing all specified architectures.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional option to pass to gcc when linking.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO backend step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional option to pass to the LTO indexing step (under --features=thin\_lto).
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple macOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible macOS version for targets. If unspecified, uses 'macos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use memprof profile.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Whether to perform symbol and dead-code strippings on linked binaries. Binary strippings will be performed if both this flag and --compilation\_mode=opt are specified.
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Additional options to pass to gcc when compiling Objective-C/C++ source files.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
Each entry should be of the form `label=value` where label refers to a platform and values
is the desired shortname to override the platform's CPU name in `$(TARGET_CPU)`
make variable and output path. Only used when `--incompatible_target_cpu_from_platform` or
`--incompatible_bep_cpu_from_platform` is true. Has highest naming priority.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to gcc when compiling certain files. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns (Also see --instrumentation\_filter). option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_copt=//foo/.\*.cc,-//foo/bar.cc\@-O0 adds the -O0 command line option to the gcc command line of all cc files in //foo/ except bar.cc.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to selectively pass to LTO backend (under --features=thin\_lto) when compiling certain backend objects. This option can be passed multiple times. Syntax: regex\_filter\@option\_1,option\_2,...,option\_n. Where regex\_filter stands for a list of include and exclude regular expression patterns. option\_1 to option\_n stand for arbitrary command line options. If an option contains a comma it has to be quoted with a backslash. Options can contain @. Only the first @ is used to split the string. Example: --per\_file\_ltobackendopt=//foo/.\*.o,-//foo/bar.o\@-O0 adds the -O0 command line option to the LTO backend command line of all o files in //foo/ except bar.o.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies a suffix to be added to the configuration directory.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Use Propeller profile information to optimize the build target.A propeller profile must consist of at least one of two files, a cc profile and a ld profile. This flag accepts a build label which must refer to the propeller profile input files. For example, the BUILD file that defines the label, in a/b/BUILD:propeller\_optimize( name = "propeller\_profile", cc\_profile = "propeller\_cc\_profile.txt", ld\_profile = "propeller\_ld\_profile.txt",)An exports\_files directive may have to be added to the corresponding package to make these files visible to Bazel. The option must be used as: --propeller\_optimize=//a/b:propeller\_profile
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of cc\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Absolute path name of ld\_profile file for Propeller Optimized builds.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Prefix to insert before the executables for the `test` and `run` commands.
If the value is `foo -bar`, and the execution command line is `test_binary -baz`,
then the final command line is `foo -bar test_binary -baz`.
This can also be a label to an executable target. Some examples are:
* `valgrind`
* `strace`
* `strace -c`
* `valgrind --quiet --num-callers=20`
* `//package:target`
* `//package:target --options`
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES)
If true, native libraries that contain identical functionality will be shared among different targets
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Stamp binaries with the date, username, hostname, workspace information, etc.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Specifies whether to strip binaries and shared libraries (using "-Wl,--strip-debug"). The default value of 'sometimes' means strip iff --compilation\_mode=fastbuild.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Additional options to pass to strip when generating a '\.stripped' binary.
*May be used multiple times; values are accumulated.*
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Comma-separated list of architectures for which to build Apple tvOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible tvOS version for target simulators and devices. If unspecified, uses 'tvos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Comma-separated list of architectures for which to build Apple visionOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Comma-separated list of architectures for which to build Apple watchOS binaries.
*May be used multiple times; values are accumulated.*
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Minimum compatible watchOS version for target simulators and devices. If unspecified, uses 'watchos\_sdk\_version'.
Tags: [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Use XbinaryFDO profile information to optimize compilation. Specify the name of default cross binary profile. When the option is used together with --fdo\_instrument/--fdo\_optimize/--fdo\_profile, those options will always prevail as if xbinary\_fdo is never specified.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
Options that affect how strictly Bazel enforces valid build inputs (rule definitions, flag combinations, etc.)
If disabled, visibility errors in target dependencies are demoted to warnings.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Whether to desugar Java 8 bytecode before dexing.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Whether to include supported Java 8 libraries in apps for legacy devices.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Checks the environments each target is compatible with and reports errors if any target has dependencies that don't support the same environments
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS)
If true, enable package()s to set the transitive\_visibility attribute to restrict which packages may depend on them.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, enforce that a java\_binary rule can't contain more than one version of the same class file on the classpath. This enforcement can break the build, or can just result in warnings.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If true, checks that a Java target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
If enabled, check testonly for prerequisite targets that are output files by looking up the testonly of the generating rule. This matches visibility checking.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
When enabled, and with experimental\_one\_version\_enforcement set to a non-NONE value, enforce one version on java\_test targets. This flag can be disabled to improve incremental test performance at the expense of missing potential one version violations.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Unless OFF, checks that a proto\_library target explicitly declares all directly used targets as dependencies.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Unless OFF, checks that a proto\_library target explicitly declares all targets used in 'import public' as exported.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, headers found through system include paths (-isystem) are also required to be declared.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`eagerness_to_exit`](#effect_tag_EAGERNESS_TO_EXIT)
Declares this build's target environment. Must be a label reference to an
`environment` rule. If specified, all top-level targets must be compatible with this
environment.
See also `--platforms`.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Options that affect the signing outputs of a build
Implementation to use to sign APKs
Tags: [`action_command_lines`](#effect_tag_ACTION_COMMAND_LINES), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
If set, and compilation mode is not 'opt', objc apps will include debug entitlements when signing.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
This option affects semantics of the Starlark language or the build API accessible to BUILD files, .bzl files, or WORKSPACE files.
If true, disallow sdk\_frameworks and weak\_sdk\_frameworks attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, make the default value true for alwayslink attributes in objc\_library and objc\_import.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Options that govern the behavior of the test environment or test runner
If true, an analysis failure of a rule target results in the target's propagation
of an instance of `AnalysisFailureInfo` containing the error description, instead
of resulting in a build failure.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Sets the maximum number of transitive dependencies through a rule attribute with
a `for_analysis_testing` configuration transition.
Exceeding this limit will result in a rule error.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Override the default resources amount for tests. The expected format is
`{resource}={value}`. If a single positive number is specified as `{value}`
it will override the default resources for all test sizes. If 4
comma-separated numbers are specified, they will override the resource
amount for respectively the `small`, `medium`, `large`, `enormous` test sizes.
Values can also be `HOST_RAM`/`HOST_CPU`, optionally followed
by `[-|*]{float}` (eg. `memory=HOST_RAM*.1,HOST_RAM*.2,HOST_RAM*.3,HOST_RAM*.4`).
The default test resources specified by this flag are overridden by explicit
resources specified in tags.
*May be used multiple times; values are accumulated.*
Specifies number of times to run each test. If any of those attempts fail for any
reason, the whole test is considered failed. Normally the value specified is
just an integer.
Example: `--runs_per_test=3` will run all tests 3 times.
Alternate syntax: `regex_filter@runs_per_test`. Where `runs_per_test` stands for
an integer value and `regex_filter` stands for a list of include and exclude
regular expression patterns (Also see --instrumentation\_filter).
Example: `--runs_per_test=//foo/.*,-//foo/bar/.*@3` runs all tests in `//foo/` except
those under `//foo/bar` three times. This option can be passed multiple times. The most
recently passed argument that matches takes precedence. If nothing matches,
the test is only run once.
*May be used multiple times; values are accumulated.*
Specifies additional environment variables to be injected into the test runner
environment. Variables can be either specified by `name`, in which
case its value will be read from the Bazel client environment, or by the
`name=value` pair.
Previously set variables can be unset via `=name`.
This option can be used multiple times to specify several variables.
Used only by the 'bazel test' command.
*May be used multiple times; values are accumulated.*
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Override the default test timeout values for test timeouts (in secs). If a single
positive integer value is specified it will override all categories. If 4
comma-separated integers are specified, they will override the timeouts for
`short`, `moderate`, `long` and `eternal` (in that order). In either form, a value of
-1 tells blaze to use its default timeouts for that category.
If true, undeclared test outputs will be archived in a zip file.
Tags: [`test_runner`](#effect_tag_TEST_RUNNER)
Options that trigger optimizations of the build time
Whether to generate and analyze .d files.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, C++ .d files will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If enabled, the dependency (.jdeps) files generated from Java compilations will be passed through in memory directly from the remote build nodes instead of being written to disk.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
When enabled, `--trim_test_configuration` will not trim the test configuration for rules
marked testonly=1. This is meant to reduce action conflict issues when non-test
rules depend on `cc_test` rules. No effect if `--trim_test_configuration` is
false.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE), [`experimental`](#metadata_tag_EXPERIMENTAL)
Whether to narrow inputs to C/C++ compilation by parsing #include lines from input files. This can improve performance and incrementality by decreasing the size of compilation input trees. However, it can also break builds because the include scanner does not fully implement C preprocessor semantics. In particular, it does not understand dynamic #include directives and ignores preprocessor conditional logic. Use at your own risk. Any issues relating to this flag that are filed will be closed. At Google without this flag your build will most likely fail.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`execution`](#effect_tag_EXECUTION), [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If set, .d files emitted by clang will be used to prune the set of inputs passed into objc compiles.
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
When building a target //a:a, process headers in all targets that //a:a depends on (if header processing is enabled for the toolchain).
Tags: [`execution`](#effect_tag_EXECUTION)
When enabled, test-related options will be cleared below the top level of the build. When this flag is active, tests cannot be built as dependencies of non-test rules, but changes to test-related options will not cause non-test rules to be re-analyzed.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`loses_incremental_state`](#effect_tag_LOSES_INCREMENTAL_STATE)
Options that affect the verbosity, format or location of logging
Print debug information during toolchain resolution. The flag takes a regex, which is checked against toolchain types and specific targets to see which to debug. Multiple regexes may be separated by commas, and then each regex is checked separately. Note: The output of this flag is very complex and will likely only be useful to experts in toolchain resolution.
Tags: [`terminal_output`](#effect_tag_TERMINAL_OUTPUT)
If enabled, visibility errors include additional diagnostic information.
Tags: [`build_file_semantics`](#effect_tag_BUILD_FILE_SEMANTICS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Options specifying or altering a generic input to a Bazel command that does not fall into other categories.
Sets a shorthand name for a Starlark flag. It takes a single key-value pair in the form
`{key}={value}` as an argument.
*May be used multiple times; values are accumulated.*
Tags: [`changes_inputs`](#effect_tag_CHANGES_INPUTS), [`non_configurable`](#metadata_tag_NON_CONFIGURABLE)
Miscellaneous options, not otherwise categorized.
Short form: `-t`
If set to `auto`, Bazel reruns a test if and only if:
* Bazel detects changes in the test or its dependencies,
* The test is marked as `external`,
* Multiple test runs were requested with `--runs_per_test`, or
* The test previously failed.
If set to `yes`, Bazel caches all test results except for tests marked as
`external`. If set to `no`, Bazel does not cache any test results.
If `on_failed` or `on_passed`, then Blaze will cancel concurrently running tests on the first
successful run with that result. This is only useful in combination with
`--runs_per_test_detects_flakes`.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, then Bazel fetches the entire coverage data directory for each test during a coverage run.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
If true, coverage for clang will generate an LCOV report.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`experimental`](#metadata_tag_EXPERIMENTAL)
Enables reduced classpaths for Java compilations.
Whether to validate java\_\* sources.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`experimental`](#metadata_tag_EXPERIMENTAL)
The number of CPUs to reserve for Turbine.
Explicitly specify a dependency to JUnit or Hamcrest in a java\_test instead of accidentally obtaining from the TestRunner's deps. Only works for bazel right now.
The Java launcher used by tools that are executed during a build.
Additional options to pass to javac when building tools that are executed during a build.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM when building tools that are executed during the build. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
If true, exclusive tests will run with sandboxed strategy. Add `local` tag to force
an exclusive test run locally
Tags: [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
If true, Bazel uses an environment with a static value for PATH and does not
inherit `LD_LIBRARY_PATH`. Use `--action_env=ENV_VARIABLE` if you want to
inherit specific environment variables from the client, but note that doing so
can prevent cross-user caching if a shared cache is used.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS), [`incompatible_change`](#metadata_tag_INCOMPATIBLE_CHANGE)
Causes the Java virtual machine of a java test to wait for a connection from a JDWP-compliant debugger (such as jdb) before starting the test. Implies -test\_output=streamed.
Expands to:
* `--test_arg=--wrapper_script_flag=--debug`
* `--test_output=streamed`
* `--test_strategy=exclusive`
* `--test_timeout=9999`
* `--nocache_test_results`
Generate dependency information (for now, compile-time classpath) per Java target.
Compile ijars directly from source.
The Java language version
The Java launcher to use when building Java binaries. If this flag is set to the empty string, the JDK launcher is used. The "launcher" attribute overrides this flag.
The Java runtime version
Additional options to pass to javac.
*May be used multiple times; values are accumulated.*
Additional options to pass to the Java VM. These options will get added to the VM startup options of each java\_binary target.
*May be used multiple times; values are accumulated.*
Specifies a binary to use to generate the list of classes that must be in the main dex when compiling legacy multidex.
Specifies a binary to use to do dexing without sharding.
Plugins to use in the build. Currently works with java\_plugin.
*May be used multiple times; values are accumulated.*
Specifies which version of ProGuard to use for code removal when building a Java binary.
The label of the proto-compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Whether to pass profile\_path to the proto compiler.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
The profile to pass to the proto compiler as profile\_path. If unset, but --proto\_profile is true (the default), infers the path from --fdo\_optimize.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile C++ protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile Java protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Label of proto\_lang\_toolchain() which describes how to compile JavaLite protos
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Additional options to pass to the protobuf compiler.
*May be used multiple times; values are accumulated.*
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS)
If true, any shard in which at least one run/attempt passes and at least one run/attempt fails gets a FLAKY status.
Absolute path to the shell executable for Bazel to use. If this is unset, but the
`BAZEL_SH` environment variable is set on the first Bazel invocation (that starts
up a Bazel server), Bazel uses that. If neither is set, Bazel uses a hard-coded
default path depending on the operating system it runs on;
* Windows: `c:/msys64/usr/bin/bash.exe`
* FreeBSD and OpenBSD: `/usr/local/bin/bash`
* All others: `/bin/bash`.
Note that using a shell that is not compatible with `bash` may lead
to build failures or runtime failures of the generated binaries.
Tags: [`loading_and_analysis`](#effect_tag_LOADING_AND_ANALYSIS)
Specifies additional options and arguments that should be passed to the test
executable. Can be used multiple times to specify several arguments.
If multiple tests are executed, each of them will receive identical arguments.
Used only by the `bazel test` command.
*May be used multiple times; values are accumulated.*
Specifies a filter to forward to the test framework. Used to limit the tests run. Note that this does not affect which targets are built.
Forwards fail fast option to the test runner. The test runner should stop execution upon first failure.
Specify strategy for test sharding:
* `explicit` to only use sharding if the `shard_count` `BUILD` attribute is
present.
* `disabled` to never use test sharding.
* `forced=k` to enforce `k` shards for testing regardless of the `shard_count` `BUILD`
attribute.
The Java language version used to execute the tools that are needed during a build
The Java runtime version used to execute tools during the build
If enabled, this option causes Java compilation to use interface jars. This will result in faster incremental compilation, but error messages can be different.
## Version Options
Options that let the user configure the intended output, affecting its value, as opposed to its existence
If set, write the version to stdout using the conventions described in the GNU standards.
Tags: [`affects_outputs`](#effect_tag_AFFECTS_OUTPUTS), [`execution`](#effect_tag_EXECUTION)
### Option Effect Tags
| | |
| - | - |
| `unknown` | This option has unknown, or undocumented, effect. |
| `no_op` | This option has literally no effect. |
| `loses_incremental_state` | Changing the value of this option can cause significant loss of incremental state, which slows builds. State could be lost due to a server restart or to invalidation of a large part of the dependency graph. |
| `changes_inputs` | This option actively changes the inputs that bazel considers for the build, such as filesystem restrictions, repository versions, or other options. |
| `affects_outputs` | This option affects bazel's outputs. This tag is intentionally broad, can include transitive affects, and does not specify the type of output it affects. |
| `build_file_semantics` | This option affects the semantics of BUILD or .bzl files. |
| `bazel_internal_configuration` | This option affects settings of bazel-internal machinery. This tag does not, on its own, mean that build artifacts are affected. |
| `loading_and_analysis` | This option affects the loading and analysis of dependencies, and the building of the dependency graph. |
| `execution` | This option affects the execution phase, such as sandboxing or remote execution related options. |
| `host_machine_resource_optimizations` | This option triggers an optimization that may be machine specific and is not guaranteed to work on all machines. The optimization could include a tradeoff with other aspects of performance, such as memory or cpu cost. |
| `eagerness_to_exit` | This option changes how eagerly bazel will exit from a failure, where a choice between continuing despite the failure and ending the invocation exists. |
| `bazel_monitoring` | This option is used to monitor bazel's behavior and performance. |
| `terminal_output` | This option affects bazel's terminal output. |
| `action_command_lines` | This option changes the command line arguments of one or more build actions. |
| `test_runner` | This option changes the testrunner environment of the build. |
### Option Metadata Tags
| | |
| - | - |
| `experimental` | This option triggers an experimental feature with no guarantees of functionality. |
| `incompatible_change` | This option triggers a breaking change. Use this option to test your migration readiness or get early access to the new feature |
| `deprecated` | This option is deprecated. It might be that the feature it affects is deprecated, or that another method of supplying the information is preferred. |
| `non_configurable` | This option cannot be changed in a transition or be used in a select() statement. |
| `fully_redacted_in_logs` | This option may contain sensitive credentials and should be redacted in logs. |
# Backward Compatibility
Source: https://bazel.build/release/backward-compatibility
This page provides information about how to handle backward compatibility,
including migrating from one release to another and how to communicate
incompatible changes.
Bazel is evolving. Minor versions released as part of an [LTS major version](/release#bazel-versioning) are fully backward-compatible. New major LTS
releases may contain incompatible changes that require some migration effort.
For more information about Bazel's release model, please check out the [Release Model](/release) page.
## Summary
1. It is recommended to use `--incompatible_*` flags for breaking changes.
2. For every `--incompatible_*` flag, a GitHub issue explains the change in
behavior and aims to provide a migration recipe.
3. Incompatible flags are recommended to be back-ported to the latest LTS
release without enabling the flag by default.
4. APIs and behavior guarded by an `--experimental_*` flag can change at any
time.
5. Never run production builds with `--experimental_*` or `--incompatible_*`
flags.
## How to follow this policy
* [For Bazel users - how to update Bazel](/install/bazelisk)
* [For contributors - best practices for incompatible changes](/contribute/breaking-changes)
* [For release managers - how to update issue labels and release](https://github.com/bazelbuild/continuous-integration/tree/master/docs/release-playbook.%6D%64)
## What is stable functionality?
In general, APIs or behaviors without `--experimental_...` flags are considered
stable, supported features in Bazel.
This includes:
* Starlark language and APIs
* Rules bundled with Bazel
* Bazel APIs such as Remote Execution APIs or Build Event Protocol
* Flags and their semantics
## Incompatible changes and migration recipes
For every incompatible change in a new release, the Bazel team aims to provide a
*migration recipe* that helps you update your code (`BUILD` and `.bzl` files, as
well as any Bazel usage in scripts, usage of Bazel API, and so on).
Incompatible changes should have an associated `--incompatible_*` flag and a
corresponding GitHub issue.
The incompatible flag and relevant changes are recommended to be back-ported to
the latest LTS release without enabling the flag by default. This allows users
to migrate for the incompatible changes before the next LTS release is
available.
## Communicating incompatible changes
The primary source of information about incompatible changes are GitHub issues
marked with an ["incompatible-change" label](https://github.com/bazelbuild/bazel/issues?q=label%3Aincompatible-change).
For every incompatible change, the issue specifies the following:
* Name of the flag controlling the incompatible change
* Description of the changed functionality
* Migration recipe
When an incompatible change is ready for migration with Bazel at HEAD
(therefore, also with the next Bazel rolling release), it should be marked with
the `migration-ready` label. The incompatible change issue is closed when the
incompatible flag is flipped at HEAD.
# Release Model
Source: https://bazel.build/release/index
As announced in [the original blog post](https://blog.bazel.build/2020/11/10/long-term-support-release.html), Bazel
4.0 and higher versions provides support for two release tracks: rolling
releases and long term support (LTS) releases. This page covers the latest
information about Bazel's release model.
## Support matrix
| LTS release | Support stage | Latest version | End of support |
| - | - | - | - |
| Bazel 10 | Rolling | [Check rolling release page](/release/rolling) | N/A |
| Bazel 9 | Active | [9.3.0](https://github.com/bazelbuild/bazel/releases/tag/9.3.0) | Dec 2028 |
| Bazel 8 | Maintenance | [8.8.1](https://github.com/bazelbuild/bazel/releases/tag/8.8.1) | Dec 2027 |
| Bazel 7 | Maintenance | [7.7.1](https://github.com/bazelbuild/bazel/releases/tag/7.7.1) | Dec 2026 |
| Bazel 6 | Deprecated | [6.6.0](https://github.com/bazelbuild/bazel/releases/tag/6.6.0) | Dec 2025 |
| Bazel 5 | Deprecated | [5.4.1](https://github.com/bazelbuild/bazel/releases/tag/5.4.1) | Jan 2025 |
| Bazel 4 | Deprecated | [4.2.4](https://github.com/bazelbuild/bazel/releases/tag/4.2.4) | Jan 2024 |
All Bazel LTS releases can be found on the [release page](https://github.com/bazelbuild/bazel/releases) on GitHub. The "Latest" badge on GitHub always points to the highest semantic version, even if a maintenance patch for an older version is released more recently.
## Release versioning
Bazel uses a *major.minor.patch* [Semantic Versioning](https://semver.org/) scheme.
* A *major release* contains features that are not backward compatible with
the previous release. Each major Bazel version is an LTS release.
* A *minor release* contains backward-compatible bug fixes and features
back-ported from the main branch.
* A *patch release* contains critical bug fixes.
Additionally, pre-release versions are indicated by appending a hyphen and a
date suffix to the next major version number.
For example, a new release of each type would result in these version numbers:
* Major: 6.0.0
* Minor: 6.1.0
* Patch: 6.1.2
* Pre-release: 7.0.0-pre.20230502.1
## Support stages
For each major Bazel version, there are four support stages:
* **Rolling**: This major version is still in pre-release, the Bazel team
publishes rolling releases from HEAD.
* **Active**: This major version is the current active LTS release. The Bazel
team backports important features and bug fixes into its minor releases.
* **Maintenance**: This major version is an old LTS release in maintenance
mode. The Bazel team only promises to backport critical bug fixes for
security issues and OS-compatibility issues into this LTS release.
* **Deprecated**: The Bazel team no longer provides support for this major
version, all users should migrate to newer Bazel LTS releases.
## Release cadence
Bazel regularly publish releases for two release tracks.
### Rolling releases
* Rolling releases are coordinated with Google Blaze release and are released
from HEAD around every two weeks. It is a preview of the next Bazel LTS
release.
* Rolling releases can ship incompatible changes. Incompatible flags are
recommended for major breaking changes, rolling out incompatible changes
should follow our [backward compatibility policy](/release/backward-compatibility).
### LTS releases
* *Major release*: A new LTS release is expected to be cut from HEAD roughly
every
12 months. Once a new LTS release is out, it immediately enters the Active
stage, and the previous LTS release enters the Maintenance stage.
* *Minor release*: New minor verions on the Active LTS track are expected to
be released once every 2 months.
* *Patch release*: New patch versions for LTS releases in Active and
Maintenance stages are expected to be released on demand for critical bug
fixes.
* A Bazel LTS release enters the Deprecated stage after being in the
Maintenance stage for 2 years.
For planned releases, please check our [release issues](https://github.com/bazelbuild/bazel/issues?q=is%3Aopen+is%3Aissue+label%3Arelease)
on Github.
## Release procedure & policies
For rolling releases, the process is straightforward: about every two weeks, a
new release is created, aligning with the same baseline as the Google internal
Blaze release. Due to the rapid release schedule, we don't backport any changes
to rolling releases.
For LTS releases, the procedure and policies below are followed:
1. Determine a baseline commit for the release.
* For a new major LTS release, the baseline commit is the HEAD of the main
branch.
* For a minor or patch release, the baseline commit is the HEAD of the
current latest version of the same LTS release.
2. Create a release branch in the name of `release-` from the baseline
commit.
3. Backport changes via PRs to the release branch.
* The community can suggest certain commits to be back-ported by replying
"`@bazel-io flag`" on relevant GitHub issues or PRs to mark them as potential
release blockers, the Bazel team triages them and decide whether to
back-port the commits.
* Only backward-compatible commits on the main branch can be back-ported,
additional minor changes to resolve merge conflicts are acceptable.
4. Backport changes using Cherry-Pick Request Issue for Bazel maintainers.
* Bazel maintainers can request to cherry-pick specific commit(s)
to a release branch. This process is initiated by creating a
cherry-pick request on GitHub. Here's how to do it.
1. Open the [cherry-pick request](https://github.com/bazelbuild/bazel/issues/new?assignees=\&labels=\&projects=\&template=cherry_pick_request.yml)
2. Fill in the request details
* Title: Provide a concise and descriptive title for the request.
* Commit ID(s): Enter the ID(s) of the commit(s) you want to
cherry-pick. If there are multiple commits, then separate
them with commas.
* Category: Specify the category of the request.
* Reviewer(s): For multiple reviewers, separate their GitHub
ID's with commas.
3. Set the milestone
* Find the "Milestone" section and click the setting.
* Select the appropriate X.Y.Z release blockers. This action
triggers the cherry-pick bot to process your request
for the "release-X.Y.Z" branch.
4. Submit the Issue
* Once all details are filled in and the miestone is set,
submit the issue.
* The cherry-pick bot will process the request and notify
if the commit(s) are eligible for cherry-picking. If
the commits are cherry-pickable, which means there's no
merge conflict while cherry-picking the commit, then
the bot will create a new pull request. When the pull
request is approved by a member of the Bazel team, the
commits are cherry-picked and merged to the release branch.
For a visual example of a completed cherry-pick request,
refer to this
[example](https://github.com/bazelbuild/bazel/issues/20230)
.
5. Identify release blockers and fix issues found on the release branch.
* The release branch is tested with the same test suite in
[postsubmit](https://buildkite.com/bazel/bazel-bazel) and
[downstream test pipeline](https://buildkite.com/bazel/bazel-at-head-plus-downstream)
on Bazel CI. The Bazel team monitors testing results of the release
branch and fixes any regressions found.
6. Create a new release candidate from the release branch when all known
release blockers are resolved.
* The release candidate is announced on
[bazel-discuss](https://groups.google.com/g/bazel-discuss),
the Bazel team monitors community bug reports for the candidate.
* If new release blockers are identified, go back to the last step and
create a new release candidate after resolving all the issues.
* New features are not allowed to be added to the release branch after the
first release candidate is created; cherry-picks are limited to critical
fixes only. If a cherry-pick is needed, the requester must answer the
following questions: Why is this change critical, and what benefits does
it provide? What is the likelihood of this change introducing a
regression?
7. Push the release candidate as the official release if no further release
blockers are found
* For patch releases, push the release at least two business days after
the last release candidate is out.
* For major and minor releases, push the release two business days after
the last release candidate is out, but not earlier than one week after
the first release candidate is out.
* The release is only pushed on a day where the next day is a business
day.
* The release is announced on
[bazel-discuss](https://groups.google.com/g/bazel-discuss),
the Bazel team monitors and addresses community bug reports for the new
release.
## Report regressions
If a user finds a regression in a new Bazel release, release candidate or even
Bazel at HEAD, please file a bug on
[GitHub](https://github.com/bazelbuild/bazel/issues). You can use
Bazelisk to bisect the culprit commit and include this information in the bug
report.
For example, if your build succeeds with Bazel 6.1.0 but fails with the second
release candidate of 6.2.0, you can do bisect via
```bash theme={null}
bazelisk --bisect=6.1.0..release-6.2.0rc2 build //foo:bar
```
You can set `BAZELISK_SHUTDOWN` or `BAZELISK_CLEAN` environment variable to run
corresponding bazel commands to reset the build state if it's needed to
reproduce the issue. For more details, check out documentation about Bazelisk
\[bisect feature] ([https://github.com/bazelbuild/bazelisk#--bisect](https://github.com/bazelbuild/bazelisk#--bisect)).
Remember to upgrade Bazelisk to the latest version to use the bisect
feature.
## Rule compatibility
If you are a rule authors and want to maintain compatibility with different
Bazel versions, please check out the [Rule Compatibility](/release/rule-compatibility) page.
# Rolling Releases
Source: https://bazel.build/release/rolling
This page contains an overview of all rolling releases, as per our
[release policy](https://bazel.build/release#rolling-releases).
[Bazelisk](https://github.com/bazelbuild/bazelisk) is the best way to use
these releases.
## Index
# Rule Compatibility
Source: https://bazel.build/release/rule-compatibility
Bazel Starlark rules can break compatibility with Bazel LTS releases in the
following two scenarios:
1. The rule breaks compatibility with future LTS releases because a feature it
depends on is removed from Bazel at HEAD.
2. The rule breaks compatibility with the current or older LTS releases because
a feature it depends on is only available in newer Bazel LTS releases.
Meanwhile, the rule itself can ship incompatible changes for their users as
well. When combined with breaking changes in Bazel, upgrading the rule version
and Bazel version can often be a source of frustration for Bazel users. This
page covers how rules authors should maintain rule compatibility with Bazel to
make it easier for users to upgrade Bazel and rules.
## Manageable migration process
While it's obviously not feasible to guarantee compatibility between every
version of Bazel and every version of the rule, our aim is to ensure that the
migration process remains manageable for Bazel users. A manageable migration
process is defined as a process where **users are not forced to upgrade the
rule's major version and Bazel's major version simultaneously**, thereby
allowing users to handle incompatible changes from one source at a time.
For example, with the following compatibility matrix:
* Migrating from rules\_foo 1.x + Bazel 4.x to rules\_foo 2.x + Bazel 5.x is not
considered manageable, as the users need to upgrade the major version of
rules\_foo and Bazel at the same time.
* Migrating from rules\_foo 2.x + Bazel 5.x to rules\_foo 3.x + Bazel 6.x is
considered manageable, as the users can first upgrade rules\_foo from 2.x to
3.x without changing the major Bazel version, then upgrade Bazel from 5.x to
6.x.
| | rules\_foo 1.x | rules\_foo 2.x | rules\_foo 3.x | HEAD |
| - | - | - | - | - |
| Bazel 4.x | ✅ | ❌ | ❌ | ❌ |
| Bazel 5.x | ❌ | ✅ | ✅ | ❌ |
| Bazel 6.x | ❌ | ❌ | ✅ | ✅ |
| HEAD | ❌ | ❌ | ❌ | ✅ |
❌: No version of the major rule version is compatible with the Bazel LTS
release.
✅: At least one version of the rule is compatible with the latest version of the
Bazel LTS release.
## Best practices
As Bazel rules authors, you can ensure a manageable migration process for users
by following these best practices:
1. The rule should follow [Semantic Versioning](https://semver.org/): minor versions of the same
major version are backward compatible.
2. The rule at HEAD should be compatible with the latest Bazel LTS release.
3. The rule at HEAD should be compatible with Bazel at HEAD. To achieve this,
you can
* Set up your own CI testing with Bazel at HEAD
* Add your project to [Bazel downstream testing](https://github.com/bazelbuild/continuous-integration/blob/master/docs/downstream-testing.md);
the Bazel team files issues to your project if breaking changes in Bazel
affect your project, and you must follow our [downstream project policies](https://github.com/bazelbuild/continuous-integration/blob/master/docs/downstream-testing.md#downstream-project-policies)
to address issues timely.
4. The latest major version of the rule must be compatible with the latest
Bazel LTS release.
5. A new major version of the rule should be compatible with the last Bazel LTS
release supported by the previous major version of the rule.
Achieving 2. and 3. is the most important task since it allows achieving 4. and
5\. naturally.
To make it easier to keep compatibility with both Bazel at HEAD and the latest
Bazel LTS release, rules authors can:
* Request backward-compatible features to be back-ported to the latest LTS
release, check out [release process](/release#release-procedure-policies)
for more details.
* Use [bazel\_features](https://github.com/bazel-contrib/bazel_features)
to do Bazel feature detection.
In general, with the recommended approaches, rules should be able to migrate for
Bazel incompatible changes and make use of new Bazel features at HEAD without
dropping compatibility with the latest Bazel LTS release.
# Build Event Protocol
Source: https://bazel.build/remote/bep
The [Build Event Protocol](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto)
(BEP) allows third-party programs to gain insight into a Bazel invocation. For
example, you could use the BEP to gather information for an IDE
plugin or a dashboard that displays build results.
The protocol is a set of [protocol buffer](https://developers.google.com/protocol-buffers/) messages with some
semantics defined on top of it. It includes information about build and test
results, build progress, the build configuration and much more. The BEP is
intended to be consumed programmatically and makes parsing Bazel’s
command line output a thing of the past.
The Build Event Protocol represents information about a build as events. A
build event is a protocol buffer message consisting of a build event identifier,
a set of child event identifiers, and a payload.
* **Build Event Identifier:** Depending on the kind of build event, it might be
an [opaque string](https://github.com/bazelbuild/bazel/blob/7.1.0/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto#L131-L140)
or [structured information](https://github.com/bazelbuild/bazel/blob/7.1.0/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto#L194-L205)
revealing more about the build event. A build event identifier is unique within
a build.
* **Children:** A build event may announce other build events, by including
their build event identifiers in its [children field](https://github.com/bazelbuild/bazel/blob/7.1.0/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto#L1276).
For example, the `PatternExpanded` build event announces the targets it expands
to as children. The protocol guarantees that all events, except for the first
event, are announced by a previous event.
* **Payload:** The payload contains structured information about a build event,
encoded as a protocol buffer message specific to that event. Note that the
payload might not be the expected type, but could be an `Aborted` message
if the build aborted prematurely.
### Build event graph
All build events form a directed acyclic graph (DAG) through their parent and child
relationships. Every build event except for the initial `BuildStarted` event is announced
by one or more earlier parent events.
#### Announcement contract
The protocol requires that every event in the stream (except `BuildStarted`) is announced in the `children` list of an earlier event:
* **Static parents:** High-level lifecycle events announce their natural children. For example, `BuildStarted` announces `PatternExpanded` and `BuildFinished`, and `PatternExpanded` announces `TargetConfigured` for each matching target.
* **Dynamic chaining via Progress:** Events discovered dynamically during evaluation that have no natural static parent—such as `NamedSetOfFiles`, `Configuration`, `WorkspaceConfig`, and `Fetch`—are announced on the fly by intervening `Progress` events before they are posted.
* **Completion invariant:** A build is considered complete if and only if all announced children have been posted or accounted for with an [`Aborted`](/remote/bep-glossary#aborted) event.
#### Announcement vs. delivery ordering
Being announced in `children` advertises that an event will eventually occur, but it does *not* imply delivery sequence:
* Bazel posts events concurrently as actions complete across worker threads.
* Some events (such as `TargetComplete`, `TestResult`, and `TestSummary`) specify order constraints (`postedAfter` in the Bazel implementation). Bazel holds back delivering these events until their prerequisite events have been posted.
* For test executions, `TargetComplete` announces initial test attempts (`TestResult`), while each retry attempt is announced by the attempt that immediately preceded it.
#### Lifecycle stages
The event graph reflects the phases of a Bazel invocation:
1. **Invocation Start:** The root [`BuildStarted`](/remote/bep-glossary#buildstarted) event is published first. It announces command metadata (`OptionsParsed`, `CommandLine`, `WorkspaceStatus`), target pattern expansion (`PatternExpanded`), and build completion (`BuildFinished`).
2. **Analysis & Configuration:** `PatternExpanded` announces `TargetConfigured` events for parsed targets. Intervening `Progress` events chain in build configurations (`Configuration`).
3. **Execution:** Each `TargetConfigured` event announces its corresponding [`TargetComplete`](/remote/bep-glossary#targetcomplete) event. `TargetComplete` references output file sets (`NamedSetOfFiles`, which are dynamically announced via intervening `Progress` events) and announces target-level summaries ([`TargetSummary`](/remote/bep-glossary#targetsummary)) as well as test events ([`TestResult`](/remote/bep-glossary#testresult), [`TestSummary`](/remote/bep-glossary#testsummary)) for test targets.
4. **Completion & Tool Logs:** The [`BuildFinished`](/remote/bep-glossary#buildfinished) event is published after command evaluation finishes, providing the authoritative exit code. It announces post-build events such as [`BuildMetrics`](/remote/bep-glossary#buildmetrics), [`BuildToolLogs`](/remote/bep-glossary#buildtoollogs), and, for `bazel run` without `--script_path`, [`ExecRequestConstructed`](/remote/bep-glossary#execrequestconstructed). These may arrive in any order; the final event of the stream has `last_message` set.
## Consuming Build Event Protocol
### Consume in binary format
To consume the BEP in a binary format:
1. Have Bazel serialize the protocol buffer messages to a file by specifying the
option `--build_event_binary_file=/path/to/file`. The file will contain
serialized protocol buffer messages with each message being length delimited.
Each message is prefixed with its length encoded as a variable length integer.
This format can be read using the protocol buffer library’s
[`parseDelimitedFrom(InputStream)`](https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/AbstractParser#parseDelimitedFrom-java.io.InputStream-)
method.
2. Then, write a program that extracts the relevant information from the
serialized protocol buffer message.
### Consume in text or JSON formats
The following Bazel command line flags will output the BEP in
human-readable formats, such as text and JSON:
```
--build_event_text_file
--build_event_json_file
```
## Build Event Service
The [Build Event Service](https://github.com/googleapis/googleapis/blob/master/google/devtools/build/v1/publish_build_event.proto)
Protocol is a generic [gRPC](https://www.grpc.io) service for publishing build events. The Build Event
Service protocol is independent of the BEP and treats BEP events as opaque bytes.
Bazel ships with a gRPC client implementation of the Build Event Service protocol that
publishes Build Event Protocol events. One can specify the endpoint to send the
events to using the `--bes_backend=HOST:PORT` flag. If your backend uses gRPC,
you must prefix the address with the appropriate scheme: `grpc://` for plaintext
gRPC and `grpcs://` for gRPC with TLS enabled.
### Build Event Service flags
Bazel has several flags related to the Build Event Service protocol, including:
* `--bes_backend`
* `--[no]bes_lifecycle_events`
* `--bes_results_url`
* `--bes_timeout`
* `--bes_instance_name`
For a description of each of these flags, see the
[Command-Line Reference](/reference/command-line-reference).
### Authentication and security
Bazel’s Build Event Service implementation also supports authentication and TLS.
These settings can be controlled using the below flags. Please note that these
flags are also used for Bazel’s Remote Execution. This implies that the Build
Event Service and Remote Execution Endpoints need to share the same
authentication and TLS infrastructure.
* `--[no]google_default_credentials`
* `--google_credentials`
* `--google_auth_scopes`
* `--tls_certificate`
* `--[no]tls_enabled`
For a description of each of these flags, see the
[Command-Line Reference](/reference/command-line-reference).
### Build Event Service and remote caching
The BEP typically contains many references to log files (test.log, test.xml,
etc. ) stored on the machine where Bazel is running. A remote BES server
typically can't access these files as they are on different machines. A way to
work around this issue is to use Bazel with [remote caching](/remote/caching).
Bazel will upload all output files to the remote cache (including files
referenced in the BEP) and the BES server can then fetch the referenced files
from the cache.
See [GitHub issue 3689](https://github.com/bazelbuild/bazel/issues/3689) for
more details.
# Build Event Protocol Examples
Source: https://bazel.build/remote/bep-examples
The full specification of the Build Event Protocol can be found in its protocol
buffer definition. However, it might be helpful to build up some intuition
before looking at the specification.
Consider a simple Bazel workspace that consists of two empty shell scripts
`foo.sh` and `foo_test.sh` and the following `BUILD` file:
```bash theme={null}
sh_library(
name = "foo_lib",
srcs = ["foo.sh"],
)
sh_test(
name = "foo_test",
srcs = ["foo_test.sh"],
deps = [":foo_lib"],
)
```
When running `bazel test ...` on this project the build graph of the generated
build events will resemble the graph below. The arrows indicate the
aforementioned parent and child relationship. Note that some build events and
most fields have been omitted for brevity.
**Figure 1.** BEP graph.
Initially, a `BuildStarted` event is published. The event informs us that the
build was invoked through the `bazel test` command and announces child events:
* `OptionsParsed`
* `WorkspaceStatus`
* `CommandLine`
* `UnstructuredCommandLine`
* `BuildMetadata`
* `BuildFinished`
* `PatternExpanded`
* `Progress`
The first three events provide information about how Bazel was invoked.
The `PatternExpanded` build event provides insight
into which specific targets the `...` pattern expanded to:
`//foo:foo_lib` and `//foo:foo_test`. It does so by declaring two
`TargetConfigured` events as children. Each `TargetConfigured` event then
declares the corresponding `TargetComplete` event as a child. Target configurations
(`Configuration`) are posted during analysis and dynamically announced by
intervening `Progress` events.
Besides the parent and child relationship, events may also refer to each other
using their build event identifiers. For example, in the above graph the
`TargetComplete` event refers to the `NamedSetOfFiles` event in its `fileSets`
field.
Build events that refer to files don’t usually embed the file
names and paths in the event. Instead, they contain the build event identifier
of a `NamedSetOfFiles` event, which will then contain the actual file names and
paths. The `NamedSetOfFiles` event allows a set of files to be reported once and
referred to by many targets. This structure is necessary because otherwise in
some cases the Build Event Protocol output size would grow quadratically with
the number of files. A `NamedSetOfFiles` event may also not have all its files
embedded, but instead refer to other `NamedSetOfFiles` events through their
build event identifiers.
Below is an instance of the `TargetComplete` event for the `//foo:foo_lib`
target from the above graph, printed in protocol buffer’s JSON representation.
The build event identifier contains the target as an opaque string and refers to
the `Configuration` event using its build event identifier. The event does not
announce any child events. The payload contains information about whether the
target was built successfully, the set of output files, and the kind of target
built.
```json theme={null}
{
"id": {
"targetCompleted": {
"label": "//foo:foo_lib",
"configuration": {
"id": "544e39a7f0abdb3efdd29d675a48bc6a"
}
}
},
"completed": {
"success": true,
"outputGroup": [{
"name": "default",
"fileSets": [{
"id": "0"
}]
}],
"targetKind": "sh_library rule"
}
}
```
## Aspect Results in BEP
Ordinary builds evaluate actions associated with `(target, configuration)`
pairs. When building with [aspects](/extending/aspects) enabled, Bazel
additionally evaluates targets associated with `(target, configuration,
aspect)` triples, for each target affected by a given enabled aspect.
Evaluation results for aspects are available in BEP despite the absence of
aspect-specific event types. For each `(target, configuration)` pair with an
applicable aspect, Bazel publishes an additional `TargetConfigured` and
`TargetComplete` event bearing the result from applying the aspect to the
target. For example, if `//:foo_lib` is built with
`--aspects=aspects/myaspect.bzl%custom_aspect`, this event would also appear in
the BEP:
```json theme={null}
{
"id": {
"targetCompleted": {
"label": "//foo:foo_lib",
"configuration": {
"id": "544e39a7f0abdb3efdd29d675a48bc6a"
},
"aspect": "aspects/myaspect.bzl%custom_aspect"
}
},
"completed": {
"success": true,
"outputGroup": [{
"name": "default",
"fileSets": [{
"id": "1"
}]
}]
}
}
```
Note: The only difference between the IDs is the presence of the `aspect`
field. A tool that does not check the `aspect` ID field and accumulates output
files by target may conflate target outputs with aspect outputs.
## Consuming `NamedSetOfFiles`
Determining the artifacts produced by a given target (or aspect) is a common
BEP use-case that can be done efficiently with some preparation. This section
discusses the recursive, shared structure offered by the `NamedSetOfFiles`
event, which matches the structure of a Starlark [Depset](/extending/depsets).
Consumers must take care to avoid quadratic algorithms when processing
`NamedSetOfFiles` events because large builds can contain tens of thousands of
such events, requiring hundreds of millions operations in a traversal with
quadratic complexity.
**Figure 2.** `NamedSetOfFiles` BEP graph.
A `NamedSetOfFiles` event always appears in the BEP stream *before* a
`TargetComplete` or `NamedSetOfFiles` event that references it. This is the
inverse of the "parent-child" event relationship, where all but the first event
appears after at least one event announcing it. A `NamedSetOfFiles` event is
announced by a `Progress` event with no semantics.
Given these ordering and sharing constraints, a typical consumer must buffer all
`NamedSetOfFiles` events until the BEP stream is exhausted. The following JSON
event stream and Python code demonstrate how to populate a map from
target/aspect to built artifacts in the "default" output group, and how to
process the outputs for a subset of built targets/aspects:
```python theme={null}
named_sets = {} # type: dict[str, NamedSetOfFiles]
outputs = {} # type: dict[str, dict[str, set[str]]]
for event in stream:
kind = event.id.WhichOneof("id")
if kind == "named_set":
named_sets[event.id.named_set.id] = event.named_set_of_files
elif kind == "target_completed":
tc = event.id.target_completed
target_id = (tc.label, tc.configuration.id, tc.aspect)
outputs[target_id] = {}
for group in event.completed.output_group:
outputs[target_id][group.name] = {fs.id for fs in group.file_sets}
for result_id in relevant_subset(outputs.keys()):
visit = outputs[result_id].get("default", [])
seen_sets = set(visit)
while visit:
set_name = visit.pop()
s = named_sets[set_name]
for f in s.files:
process_file(result_id, f)
for fs in s.file_sets:
if fs.id not in seen_sets:
visit.add(fs.id)
seen_sets.add(fs.id)
```
# Build Event Protocol Glossary
Source: https://bazel.build/remote/bep-glossary
Each BEP event type has its own semantics, minimally documented in
[build\_event\_stream.proto](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/buildeventstream/proto/build_event_stream.proto).
The following glossary describes each event type.
## Aborted
Unlike other events, `Aborted` does not have a corresponding ID type, because
the `Aborted` event *replaces* events of other types. This event indicates that
the build terminated early and the event ID it appears under was not produced
normally. `Aborted` contains an enum and human-friendly description to explain
why the build did not complete.
For example, if a build is evaluating a target when the user interrupts Bazel,
BEP contains an event like the following:
```json theme={null}
{
"id": {
"targetCompleted": {
"label": "//:foo",
"configuration": {
"id": "544e39a7f0abdb3efdd29d675a48bc6a"
}
}
},
"aborted": {
"reason": "USER_INTERRUPTED"
}
}
```
## ActionExecuted
Provides details about the execution of a specific
[Action](/rules/lib/builtins/actions) in a build. By default, this event is
included in the BEP only for failed actions, to support identifying the root cause
of build failures. Users may set the `--build_event_publish_all_actions` flag
to include all `ActionExecuted` events.
## BuildFinished
A single `BuildFinished` event is sent after the command is complete and
includes the exit code for the command. This event provides authoritative
success/failure information.
## BuildMetadata
Contains the parsed contents of the `--build_metadata` flag. This event exists
to support Bazel integration with other tooling by plumbing external data (such as
identifiers).
## BuildMetrics
A single `BuildMetrics` event is sent at the end of every command and includes
counters/gauges useful for quantifying the build tool's behavior during the
command. These metrics indicate work actually done and does not count cached
work that is reused.
Note that `memory_metrics` may not be populated if there was no Java garbage
collection during the command's execution. Users may set the
`--memory_profile=/dev/null` option which forces the garbage
collector to run at the end of the command to populate `memory_metrics`.
```json theme={null}
{
"id": {
"buildMetrics": {}
},
"buildMetrics": {
"actionSummary": {
"actionsExecuted": "1"
},
"memoryMetrics": {},
"targetMetrics": {
"targetsLoaded": "9",
"targetsConfigured": "19"
},
"packageMetrics": {
"packagesLoaded": "5"
},
"timingMetrics": {
"cpuTimeInMs": "1590",
"wallTimeInMs": "359"
}
}
}
```
## BuildStarted
The first event in a BEP stream, `BuildStarted` includes metadata describing the
command before any meaningful work begins.
## BuildToolLogs
A single `BuildToolLogs` event is sent at the end of a command, including URIs
of files generated by the build tool that may aid in understanding or debugging
build tool behavior. Some information may be included inline.
```json theme={null}
{
"id": {
"buildToolLogs": {}
},
"lastMessage": true,
"buildToolLogs": {
"log": [
{
"name": "elapsed time",
"contents": "MC4xMjEwMDA="
},
{
"name": "process stats",
"contents": "MSBwcm9jZXNzOiAxIGludGVybmFsLg=="
},
{
"name": "command.profile.gz",
"uri": "file:///tmp/.cache/bazel/_bazel_foo/cde87985ad0bfef34eacae575224b8d1/command.profile.gz"
}
]
}
}
```
## CommandLine
The BEP contains multiple `CommandLine` events containing representations of all
command-line arguments (including options and uninterpreted arguments).
Each `CommandLine` event has a label in its `StructuredCommandLineId` that
indicates which representation it conveys; three such events appear in the BEP:
* `"original"`: Reconstructed commandline as Bazel received it from the Bazel
client, without startup options sourced from .rc files.
* `"canonical"`: The effective commandline with .rc files expanded and
invocation policy applied.
* `"tool"`: Populated from the `--experimental_tool_command_line` option. This
is useful to convey the command-line of a tool wrapping Bazel through the BEP.
This could be a base64-encoded `CommandLine` binary protocol buffer message
which is used directly, or a string which is parsed but not interpreted (as
the tool's options may differ from Bazel's).
## Configuration
A `Configuration` event is sent for every [`configuration`](/extending/config)
used in the top-level targets in a build. At least one configuration event is
always be present. The `id` is reused by the `TargetConfigured` and
`TargetComplete` event IDs and is necessary to disambiguate those events in
multi-configuration builds.
```json theme={null}
{
"id": {
"configuration": {
"id": "a5d130b0966b4a9ca2d32725aa5baf40e215bcfc4d5cdcdc60f5cc5b4918903b"
}
},
"configuration": {
"mnemonic": "k8-fastbuild",
"platformName": "k8",
"cpu": "k8",
"makeVariable": {
"COMPILATION_MODE": "fastbuild",
"TARGET_CPU": "k8",
"GENDIR": "bazel-out/k8-fastbuild/bin",
"BINDIR": "bazel-out/k8-fastbuild/bin"
}
}
}
```
## ConvenienceSymlinksIdentified
**Experimental.** If the `--experimental_convenience_symlinks_bep_event`
option is set, a single `ConvenienceSymlinksIdentified` event is produced by
`build` commands to indicate how symlinks in the workspace should be managed.
This enables building tools that invoke Bazel remotely then arrange the local
workspace as if Bazel had been run locally.
```json theme={null}
{
"id": {
"convenienceSymlinksIdentified":{}
},
"convenienceSymlinksIdentified": {
"convenienceSymlinks": [
{
"path": "bazel-bin",
"action": "CREATE",
"target": "execroot/google3/bazel-out/k8-fastbuild/bin"
},
{
"path": "bazel-genfiles",
"action": "CREATE",
"target": "execroot/google3/bazel-out/k8-fastbuild/genfiles"
},
{
"path": "bazel-out",
"action": "CREATE",
"target": "execroot/google3/bazel-out"
}
]
}
}
```
## ExecRequestConstructed
Published by `bazel run` (unless `--script_path` is set) after a successful
build, before the requested binary is executed. This event contains the
execution details, such as the working directory, command-line arguments
(`argv`), and environment variables.
## Fetch
Indicates that a Fetch operation occurred as a part of the command execution.
Unlike other events, if a cached fetch result is re-used, this event does not
appear in the BEP stream.
## NamedSetOfFiles
`NamedSetOfFiles` events report a structure matching a
[`depset`](/extending/depsets) of files produced during command evaluation.
Transitively included depsets are identified by `NamedSetOfFilesId`.
For more information on interpreting a stream's `NamedSetOfFiles` events, see the
[BEP examples page](/remote/bep-examples#consuming-namedsetoffiles).
## OptionsParsed
A single `OptionsParsed` event lists all options applied to the command,
separating startup options from command options. It also includes the
[InvocationPolicy](/reference/command-line-reference#flag--invocation_policy), if any.
```json theme={null}
{
"id": {
"optionsParsed": {}
},
"optionsParsed": {
"startupOptions": [
"--max_idle_secs=10800",
"--noshutdown_on_low_sys_mem",
"--connect_timeout_secs=30",
"--output_user_root=/tmp/.cache/bazel/_bazel_foo",
"--output_base=/tmp/.cache/bazel/_bazel_foo/a61fd0fbee3f9d6c1e30d54b68655d35",
"--deep_execroot",
"--idle_server_tasks",
"--write_command_log",
"--nowatchfs",
"--nofatal_event_bus_exceptions",
"--nowindows_enable_symlinks",
"--noclient_debug",
],
"cmdLine": [
"--enable_platform_specific_config",
"--build_event_json_file=/tmp/bep.json"
],
"explicitCmdLine": [
"--build_event_json_file=/tmp/bep.json"
],
"invocationPolicy": {}
}
}
```
## PatternExpanded
`PatternExpanded` events indicate the set of all targets that match the patterns
supplied on the commandline. For successful commands, a single event is present
with all patterns in the `PatternExpandedId` and all targets in the
`PatternExpanded` event's *children*. If the pattern expands to any
`test_suite`s the set of test targets included by the `test_suite`. For each
pattern that fails to resolve, BEP contains an additional [`Aborted`](#aborted)
event with a `PatternExpandedId` identifying the pattern.
```json theme={null}
{
"id": {
"pattern": {
"pattern":["//base:all"]
}
},
"children": [
{"targetConfigured":{"label":"//base:foo"}},
{"targetConfigured":{"label":"//base:foobar"}}
],
"expanded": {
"testSuiteExpansions": {
"suiteLabel": "//base:suite",
"testLabels": "//base:foo_test"
}
}
}
```
## Progress
Progress events contain the standard output and standard error produced by Bazel
during command execution. These events are also auto-generated as needed to
announce events that have not been announced by a logical "parent" event (in
particular, [NamedSetOfFiles](#namedsetoffiles).)
## SkyValueUploaded
**Experimental.** Emitted when Bazel uploads a Skyframe node or value to remote
analysis cache storage. This event includes the Skyframe node key, version, and
fingerprint to support remote analysis caching workflows.
## TargetComplete
For each `(target, configuration, aspect)` combination that completes the
execution phase, a `TargetComplete` event is included in BEP. The event contains
the target's success/failure and the target's requested output groups.
```json theme={null}
{
"id": {
"targetCompleted": {
"label": "//examples/py:bep",
"configuration": {
"id": "a5d130b0966b4a9ca2d32725aa5baf40e215bcfc4d5cdcdc60f5cc5b4918903b"
}
}
},
"completed": {
"success": true,
"outputGroup": [
{
"name": "default",
"fileSets": [
{
"id": "0"
}
]
}
]
}
}
```
## TargetConfigured
For each Target that completes the analysis phase, a `TargetConfigured` event is
included in BEP. This is the authoritative source for a target's "rule kind"
attribute. The configuration(s) applied to the target appear in the announced
*children* of the event.
For example, building with the `--experimental_multi_cpu` options may produce
the following `TargetConfigured` event for a single target with two
configurations:
```json theme={null}
{
"id": {
"targetConfigured": {
"label": "//starlark_configurations/multi_arch_binary:foo"
}
},
"children": [
{
"targetCompleted": {
"label": "//starlark_configurations/multi_arch_binary:foo",
"configuration": {
"id": "c62b30c8ab7b9fc51a05848af9276529842a11a7655c71327ade26d7c894c818"
}
}
},
{
"targetCompleted": {
"label": "//starlark_configurations/multi_arch_binary:foo",
"configuration": {
"id": "eae0379b65abce68d54e0924c0ebcbf3d3df26c6e84ef7b2be51e8dc5b513c99"
}
}
}
],
"configured": {
"targetKind": "foo_binary rule"
}
}
```
## TargetSummary
For each `(target, configuration)` pair that is executed, a `TargetSummary`
event is included with an aggregate success result encompassing the configured
target's execution and all aspects applied to that configured target.
## TestResult
If testing is requested, a `TestResult` event is sent for each test attempt,
shard, and run per test. This allows BEP consumers to identify precisely which
test actions failed their tests and identify the test outputs (such as logs,
test.xml files) for each test action.
## TestProgress
May be emitted while a test action is running. The event contains a URI that
can be queried for information about the active test run, such as live output.
The URI is not guaranteed to be available after the test completes and
publishes its final [`TestResult`](#testresult).
## TestSummary
If testing is requested, a `TestSummary` event is sent for each test `(target,
configuration)`, containing information necessary to interpret the test's
results. The number of attempts, shards and runs per test are included to enable
BEP consumers to differentiate artifacts across these dimensions. The attempts
and runs per test are considered while producing the aggregate `TestStatus` to
differentiate `FLAKY` tests from `FAILED` tests.
## UnstructuredCommandLine
Unlike [CommandLine](#commandline), this event carries the unparsed commandline
flags in string form as encountered by the build tool after expanding all
[`.bazelrc`](/run/bazelrc) files and
considering the `--config` flag.
The `UnstructuredCommandLine` event may be relied upon to precisely reproduce a
given command execution.
## WorkspaceConfig
A single `WorkspaceConfig` event contains configuration information regarding the
workspace, such as the execution root.
## WorkspaceStatus
A single `WorkspaceStatus` event contains the result of the [workspace status command](/docs/user-manual#workspace-status).
# Debugging Remote Cache Hits for Local Execution
Source: https://bazel.build/remote/cache-local
This page describes how to investigate cache misses in the context of local
execution.
This page assumes that you have a build and/or test that successfully builds
locally and is set up to utilize remote caching, and that you want to ensure
that the remote cache is being effectively utilized.
For tips on how to check your cache hit rate and how to compare the execution
logs between two Bazel invocations, see
[Debugging Remote Cache Hits for Remote Execution](/remote/cache-remote).
Everything presented in that guide also applies to remote caching with local
execution. However, local execution presents some additional challenges.
## Checking your cache hit rate
Successful remote cache hits will show up in the status line, similar to
[Cache Hits rate with Remote Execution](/remote/cache-remote#check-cache-hits).
In the standard output of your Bazel run, you will see something like the
following:
```none theme={null}
INFO: 7 processes: 3 remote cache hit, 4 linux-sandbox.
```
This means that out of 7 attempted actions, 3 got a remote cache hit and 4
actions did not have cache hits and were executed locally using `linux-sandbox`
strategy. Local cache hits are not included in this summary. If you are getting
0 processes (or a number lower than expected), run `bazel clean` followed by
your build/test command.
## Troubleshooting cache hits
If you are not getting the cache hit rate you are expecting, do the following:
### Ensure successful communication with the remote endpoint
To ensure your build is successfully communicating with the remote cache, follow
the steps in this section.
1. Check your output for warnings
With remote execution, a failure to talk to the remote endpoint would fail
your build. On the other hand, a cacheable local build would not fail if it
cannot cache. Check the output of your Bazel invocation for warnings, such
as:
```none theme={null}
WARNING: Error reading from the remote cache:
```
or
```none theme={null}
WARNING: Error writing to the remote cache:
```
Such warnings will be followed by the error message detailing the connection
problem that should help you debug: for example, mistyped endpoint name or
incorrectly set credentials. Find and address any such errors. If the error
message you see does not give you enough information, try adding
`--verbose_failures`.
2. Follow the steps from [Troubleshooting cache hits for remote execution](/remote/cache-remote#troubleshooting_cache_hits) to
ensure that your cache-writing Bazel invocations are able to get cache hits
on the same machine and across machines.
3. Ensure your cache-reading Bazel invocations can get cache hits.
a. Since cache-reading Bazel invocations will have a different command-line set
up, take additional care to ensure that they are properly set up to
communicate with the remote cache. Ensure the `--remote_cache` flag is set
and there are no warnings in the output.
b. Ensure your cache-reading Bazel invocations build the same targets as the
cache-writing Bazel invocations.
c. Follow the same steps as to [ensure caching across machines](/remote/cache-remote#caching-across-machines),
to ensure caching from your cache-writing Bazel invocation to your
cache-reading Bazel invocation.
# Debugging Remote Cache Hits for Remote Execution
Source: https://bazel.build/remote/cache-remote
This page describes how to check your cache hit rate and how to investigate
cache misses in the context of remote execution.
This page assumes that you have a build and/or test that successfully
utilizes remote execution, and you want to ensure that you are effectively
utilizing remote cache.
## Checking your cache hit rate
In the standard output of your Bazel run, look at the `INFO` line that lists
processes, which roughly correspond to Bazel actions. That line details
where the action was run. Look for the `remote` label, which indicates an action
executed remotely, `linux-sandbox` for actions executed in a local sandbox,
and other values for other execution strategies. An action whose result came
from a remote cache is displayed as `remote cache hit`.
For example:
```none theme={null}
INFO: 11 processes: 6 remote cache hit, 3 internal, 2 remote.
```
In this example there were 6 remote cache hits, and 2 actions did not have
cache hits and were executed remotely. The 3 internal part can be ignored.
It is typically tiny internal actions, such as creating symbolic links. Local
cache hits are not included in this summary. If you are getting 0 processes
(or a number lower than expected), run `bazel clean` followed by your build/test
command.
## Troubleshooting cache hits
If you are not getting the cache hit rate you are expecting, do the following:
### Ensure re-running the same build/test command produces cache hits
1. Run the build(s) and/or test(s) that you expect to populate the cache. The
first time a new build is run on a particular stack, you can expect no remote
cache hits. As part of remote execution, action results are stored in the
cache and a subsequent run should pick them up.
2. Run `bazel clean`. This command cleans your local cache, which allows
you to investigate remote cache hits without the results being masked by
local cache hits.
3. Run the build(s) and test(s) that you are investigating again (on the same
machine).
4. Check the `INFO` line for cache hit rate. If you see no processes except
`remote cache hit` and `internal`, then your cache is being correctly populated and
accessed. In that case, skip to the next section.
5. A likely source of discrepancy is something non-hermetic in the build causing
the actions to receive different action keys across the two runs. To find
those actions, do the following:
a. Re-run the build(s) or test(s) in question to obtain execution logs:
```posix-terminal theme={null}
bazel clean
bazel --optional-flags build //your:target --execution_log_compact_file=/tmp/exec1.log
```
b. [Compare the execution logs](#compare-logs) between the
two runs. Ensure that the actions are identical across the two log files.
Discrepancies provide a clue about the changes that occurred between the
runs. Update your build to eliminate those discrepancies.
If you are able to resolve the caching problems and now the repeated run
produces all cache hits, skip to the next section.
If your action IDs are identical but there are no cache hits, then something
in your configuration is preventing caching. Continue with this section to
check for common problems.
6. Check that all actions in the execution log have `cacheable` set to true. If
`cacheable` does not appear in the execution log for a give action, that
means that the corresponding rule may have a `no-cache` tag in its
definition in the `BUILD` file. Look at the `mnemonic` and `target_label`
fields in the execution log to help determine where the action is coming
from.
7. If the actions are identical and `cacheable` but there are no cache hits, it
is possible that your command line includes `--noremote_accept_cached` which
would disable cache lookups for a build.
If figuring out the actual command line is difficult, use the canonical
command line from the
[Build Event Protocol](/remote/bep)
as follows:
a. Add `--build_event_text_file=/tmp/bep.txt` to your Bazel command to get
the text version of the log.
b. Open the text version of the log and search for the
`structured_command_line` message with `command_line_label: "canonical"`.
It will list all the options after expansion.
c. Search for `remote_accept_cached` and check whether it's set to `false`.
d. If `remote_accept_cached` is `false`, determine where it is being
set to `false`: either at the command line or in a
[bazelrc](/run/bazelrc#bazelrc-file-locations) file.
### Ensure caching across machines
After cache hits are happening as expected on the same machine, run the
same build(s)/test(s) on a different machine. If you suspect that caching is
not happening across machines, do the following:
1. Make a small modification to your build to avoid hitting existing caches.
2. Run the build on the first machine:
```posix-terminal theme={null}
bazel clean
bazel ... build ... --execution_log_compact_file=/tmp/exec1.log
```
3. Run the build on the second machine, ensuring the modification from step 1
is included:
```posix-terminal theme={null}
bazel clean
bazel ... build ... --execution_log_compact_file=/tmp/exec2.log
```
4. [Compare the execution logs](#compare-logs) for the two
runs. If the logs are not identical, investigate your build configurations
for discrepancies as well as properties from the host environment leaking
into either of the builds.
## Comparing the execution logs
The execution log contains records of actions executed during the build.
Each record describes both the inputs (not only files, but also command line
arguments, environment variables, etc) and the outputs of the action. Thus,
examination of the log can reveal why an action was reexecuted.
The execution log can be produced in one of three formats:
compact (`--execution_log_compact_file`),
binary (`--execution_log_binary_file`) or JSON (`--execution_log_json_file`).
The compact format is recommended, as it produces much smaller files with very
little runtime overhead. The following instructions work for any format. You
can also convert between them using the `//src/tools/execlog:converter` tool.
To compare logs for two builds that are not sharing cache hits as expected,
do the following:
1. Get the execution logs from each build and store them as `/tmp/exec1.log` and
`/tmp/exec2.log`.
2. Download the Bazel source code and build the `//src/tools/execlog:parser`
tool:
git clone [https://github.com/bazelbuild/bazel.git](https://github.com/bazelbuild/bazel.git)
cd bazel
bazel build //src/tools/execlog:parser
3. Use the `//src/tools/execlog:parser` tool to convert the logs into a
human-readable text format. In this format, the actions in the second log are
sorted to match the order in the first log, making a comparison easier.
bazel-bin/src/tools/execlog/parser \
\--log\_path=/tmp/exec1.log \
\--log\_path=/tmp/exec2.log \
\--output\_path=/tmp/exec1.log.txt \
\--output\_path=/tmp/exec2.log.txt
4. Use your favourite text differ to diff `/tmp/exec1.log.txt` and
`/tmp/exec2.log.txt`.
# Remote Caching
Source: https://bazel.build/remote/caching
This page covers remote caching, setting up a server to host the cache, and
running builds using the remote cache.
A remote cache is used by a team of developers and/or a continuous integration
(CI) system to share build outputs. If your build is reproducible, the
outputs from one machine can be safely reused on another machine, which can
make builds significantly faster.
## Overview
Bazel breaks a build into discrete steps, which are called actions. Each action
has inputs, output names, a command line, and environment variables. Required
inputs and expected outputs are declared explicitly for each action.
You can set up a server to be a remote cache for build outputs, which are these
action outputs. These outputs consist of a list of output file names and the
hashes of their contents. With a remote cache, you can reuse build outputs
from another user's build rather than building each new output locally.
To use remote caching:
* Set up a server as the cache's backend
* Configure the Bazel build to use the remote cache
* Use Bazel version 0.10.0 or later
The remote cache stores two types of data:
* The action cache, which is a map of action hashes to action result metadata.
* A content-addressable store (CAS) of output files.
Note that the remote cache additionally stores the stdout and stderr for every
action. Inspecting the stdout/stderr of Bazel thus is not a good signal for
[estimating cache hits](/remote/cache-local).
### How a build uses remote caching
Once a server is set up as the remote cache, you use the cache in multiple
ways:
* Read and write to the remote cache
* Read and/or write to the remote cache except for specific targets
* Only read from the remote cache
* Not use the remote cache at all
When you run a Bazel build that can read and write to the remote cache,
the build follows these steps:
1. Bazel creates the graph of targets that need to be built, and then creates
a list of required actions. Each of these actions has declared inputs
and output filenames.
2. Bazel checks your local machine for existing build outputs and reuses any
that it finds.
3. Bazel checks the cache for existing build outputs. If the output is found,
Bazel retrieves the output. This is a cache hit.
4. For required actions where the outputs were not found, Bazel executes the
actions locally and creates the required build outputs.
5. New build outputs are uploaded to the remote cache.
## Setting up a server as the cache's backend
You need to set up a server to act as the cache's backend. A HTTP/1.1
server can treat Bazel's data as opaque bytes and so many existing servers
can be used as a remote caching backend. Bazel's
[HTTP Caching Protocol](#http-caching) is what supports remote
caching.
You are responsible for choosing, setting up, and maintaining the backend
server that will store the cached outputs. When choosing a server, consider:
* Networking speed. For example, if your team is in the same office, you may
want to run your own local server.
* Security. The remote cache will have your binaries and so needs to be secure.
* Ease of management. For example, Google Cloud Storage is a fully managed service.
There are many backends that can be used for a remote cache. Some options
include:
* [nginx](#nginx)
* [bazel-remote](#bazel-remote)
* [Google Cloud Storage](#cloud-storage)
### nginx
nginx is an open source web server. With its \[WebDAV module], it can be
used as a remote cache for Bazel. On Debian and Ubuntu you can install the
`nginx-extras` package. On macOS nginx is available via Homebrew:
```posix-terminal theme={null}
brew tap denji/nginx
brew install nginx-full --with-webdav
```
Below is an example configuration for nginx. Note that you will need to
change `/path/to/cache/dir` to a valid directory where nginx has permission
to write and read. You may need to change `client_max_body_size` option to a
larger value if you have larger output files. The server will require other
configuration such as authentication.
Example configuration for `server` section in `nginx.conf`:
```nginx theme={null}
location /cache/ {
# The path to the directory where nginx should store the cache contents.
root /path/to/cache/dir;
# Allow PUT
dav_methods PUT;
# Allow nginx to create the /ac and /cas subdirectories.
create_full_put_path on;
# The maximum size of a single file.
client_max_body_size 1G;
allow all;
}
```
### bazel-remote
bazel-remote is an open source remote build cache that you can use on
your infrastructure. It has been successfully used in production at
several companies since early 2018. Note that the Bazel project does
not provide technical support for bazel-remote.
This cache stores contents on disk and also provides garbage collection
to enforce an upper storage limit and clean unused artifacts. The cache is
available as a [docker image](https://hub.docker.com/r/buchgr/bazel-remote-cache/) and its code is available on
[GitHub](https://github.com/buchgr/bazel-remote/).
Both the REST and gRPC remote cache APIs are supported.
Refer to the [GitHub](https://github.com/buchgr/bazel-remote/)
page for instructions on how to use it.
### Google Cloud Storage
\[Google Cloud Storage] is a fully managed object store which provides an
HTTP API that is compatible with Bazel's remote caching protocol. It requires
that you have a Google Cloud account with billing enabled.
To use Cloud Storage as the cache:
1. [Create a storage bucket](https://cloud.google.com/storage/docs/creating-buckets).
Ensure that you select a bucket location that's closest to you, as network bandwidth
is important for the remote cache.
2. Create a service account for Bazel to authenticate to Cloud Storage. See
[Creating a service account](https://cloud.google.com/iam/docs/creating-managing-service-accounts#creating_a_service_account).
3. Generate a secret JSON key and then pass it to Bazel for authentication. Store
the key securely, as anyone with the key can read and write arbitrary data
to/from your GCS bucket.
4. Connect to Cloud Storage by adding the following flags to your Bazel command:
* Pass the following URL to Bazel by using the flag:
`--remote_cache=https://storage.googleapis.com/bucket-name` where `bucket-name` is the name of your storage bucket.
* Pass the authentication key using the flag: `--google_credentials=/path/to/your/secret-key.json`, or
`--google_default_credentials` to use [Application Authentication](https://cloud.google.com/docs/authentication/production).
5. You can configure Cloud Storage to automatically delete old files. To do so, see
[Managing Object Lifecycles](https://cloud.google.com/storage/docs/managing-lifecycles).
### Other servers
You can set up any HTTP/1.1 server that supports PUT and GET as the cache's
backend. Users have reported success with caching backends such as [Hazelcast](https://hazelcast.com),
[Apache httpd](http://httpd.apache.org), and [AWS S3](https://aws.amazon.com/s3).
## Authentication
As of version 0.11.0 support for HTTP Basic Authentication was added to Bazel.
You can pass a username and password to Bazel via the remote cache URL. The
syntax is `https://username:password@hostname.com:port/path`. Note that
HTTP Basic Authentication transmits username and password in plaintext over the
network and it's thus critical to always use it with HTTPS.
## HTTP caching protocol
Bazel supports remote caching via HTTP/1.1. The protocol is conceptually simple:
Binary data (BLOB) is uploaded via PUT requests and downloaded via GET requests.
Action result metadata is stored under the path `/ac/` and output files are stored
under the path `/cas/`.
For example, consider a remote cache running under `http://localhost:8080/cache`.
A Bazel request to download action result metadata for an action with the SHA256
hash `01ba4719...` will look as follows:
```http theme={null}
GET /cache/ac/01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b HTTP/1.1
Host: localhost:8080
Accept: */*
Connection: Keep-Alive
```
A Bazel request to upload an output file with the SHA256 hash `15e2b0d3...` to
the CAS will look as follows:
```http theme={null}
PUT /cache/cas/15e2b0d3c33891ebb0f1ef609ec419420c20e320ce94c65fbc8c3312448eb225 HTTP/1.1
Host: localhost:8080
Accept: */*
Content-Length: 9
Connection: Keep-Alive
0x310x320x330x340x350x360x370x380x39
```
## Run Bazel using the remote cache
Once a server is set up as the remote cache, to use the remote cache you
need to add flags to your Bazel command. See list of configurations and
their flags below.
You may also need configure authentication, which is specific to your
chosen server.
You may want to add these flags in a `.bazelrc` file so that you don't
need to specify them every time you run Bazel. Depending on your project and
team dynamics, you can add flags to a `.bazelrc` file that is:
* On your local machine
* In your project's workspace, shared with the team
* On the CI system
### Read from and write to the remote cache
Take care in who has the ability to write to the remote cache. You may want
only your CI system to be able to write to the remote cache.
Use the following flag to read from and write to the remote cache:
```posix-terminal theme={null}
build --remote_cache=http://your.host:port
```
Besides `HTTP`, the following protocols are also supported: `HTTPS`, `grpc`, `grpcs`.
Use the following flag in addition to the one above to only read from the
remote cache:
```posix-terminal theme={null}
build --remote_upload_local_results=false
```
### Exclude specific targets from using the remote cache
To exclude specific targets from using the remote cache, tag the target with
`no-remote-cache`. For example:
```starlark theme={null}
java_library(
name = "target",
tags = ["no-remote-cache"],
)
```
### Delete content from the remote cache
Deleting content from the remote cache is part of managing your server.
How you delete content from the remote cache depends on the server you have
set up as the cache. When deleting outputs, either delete the entire cache,
or delete old outputs.
The cached outputs are stored as a set of names and hashes. When deleting
content, there's no way to distinguish which output belongs to a specific
build.
You may want to delete content from the cache to:
* Create a clean cache after a cache was poisoned
* Reduce the amount of storage used by deleting old outputs
### Unix sockets
The remote HTTP cache supports connecting over unix domain sockets. The behavior
is similar to curl's `--unix-socket` flag. Use the following to configure unix
domain socket:
```posix-terminal theme={null}
build --remote_cache=http://your.host:port
build --remote_proxy=unix:/path/to/socket
```
This feature is unsupported on Windows.
## Disk cache
Bazel can use a directory on the file system as a remote cache. This is
useful for sharing build artifacts when switching branches and/or working
on multiple workspaces of the same project, such as multiple checkouts.
Enable the disk cache as follows:
```posix-terminal theme={null}
build --disk_cache=path/to/build/cache
```
You can also run `build --disk_cache` with no value to use a default location
under your [output user root](/reference/user-manual#output-user-root)
(`/cache/disk`), alongside the repository cache. Use
`build --nodisk_cache` to disable the disk cache explicitly.
You can pass a user-specific path to the `--disk_cache` flag using the `~` alias
(Bazel will substitute the current user's home directory). This comes in handy
when enabling the disk cache for all developers of a project via the project's
checked in `.bazelrc` file.
### Garbage collection
Starting with Bazel 7.4, you can use `--experimental_disk_cache_gc_max_size` and
`--experimental_disk_cache_gc_max_age` to set a maximum size for the disk cache
or for the age of individual cache entries. Bazel will automatically garbage
collect the disk cache while idling between builds; the idle timer can be set
with `--experimental_disk_cache_gc_idle_delay` (defaulting to 5 minutes).
As an alternative to automatic garbage collection, we also provide a [tool](https://github.com/bazelbuild/bazel/tree/master/src/tools/diskcache) to run a
garbage collection on demand.
## Known issues
**Input file modification during a build**
When an input file is modified during a build, Bazel might upload invalid
results to the remote cache. You can enable a change detection with
the `--experimental_guard_against_concurrent_changes` flag. There
are no known issues and it will be enabled by default in a future release.
See \[issue #3360] for updates. Generally, avoid modifying source files during a
build.
**Environment variables leaking into an action**
An action definition contains environment variables. This can be a problem for
sharing remote cache hits across machines. For example, environments with
different `$PATH` variables won't share cache hits. Only environment variables
explicitly whitelisted via `--action_env` are included in an action
definition. Bazel's Debian/Ubuntu package used to install `/etc/bazel.bazelrc`
with a whitelist of environment variables including `$PATH`. If you are getting
fewer cache hits than expected, check that your environment doesn't have an old
`/etc/bazel.bazelrc` file.
**Bazel does not track tools outside a workspace**
Bazel currently does not track tools outside a workspace. This can be a
problem if, for example, an action uses a compiler from `/usr/bin/`. Then,
two users with different compilers installed will wrongly share cache hits
because the outputs are different but they have the same action hash. See
[issue #4558](https://github.com/bazelbuild/bazel/issues/4558) for updates.
**Incremental in-memory state is lost when running builds inside docker containers**
Bazel uses server/client architecture even when running in single docker container.
On the server side, Bazel maintains an in-memory state which speeds up builds.
When running builds inside docker containers such as in CI, the in-memory state is lost
and Bazel must rebuild it before using the remote cache.
## External links
* **Your Build in a Datacenter:** The Bazel team gave a [talk](https://fosdem.org/2018/schedule/event/datacenter_build/) about remote caching and execution at FOSDEM 2018.
* **Faster Bazel builds with remote caching: a benchmark:** Nicolò Valigi wrote a [blog post](https://nicolovaligi.com/faster-bazel-remote-caching-benchmark.html)
in which he benchmarks remote caching in Bazel.
* [Adapting Rules for Remote Execution](/remote/rules)
* [Troubleshooting Remote Execution](/remote/sandbox)
* [WebDAV module](https://nginx.org/en/docs/http/ngx_http_dav_module.html)
* [Docker image](https://hub.docker.com/r/buchgr/bazel-remote-cache/)
* [bazel-remote](https://github.com/buchgr/bazel-remote/)
* [Google Cloud Storage](https://cloud.google.com/storage)
* [Google Cloud Console](https://cloud.google.com/console)
* [Bucket locations](https://cloud.google.com/storage/docs/bucket-locations)
* [Hazelcast](https://hazelcast.com)
* [Apache httpd](http://httpd.apache.org)
* [AWS S3](https://aws.amazon.com/s3)
* [issue #3360](https://github.com/bazelbuild/bazel/issues/3360)
* [gRPC](https://grpc.io/)
* [gRPC protocol](https://github.com/bazelbuild/remote-apis/blob/main/build/bazel/remote/execution/v2/remote_execution.proto)
* [Buildbarn](https://github.com/buildbarn)
* [Buildfarm](https://github.com/bazelbuild/bazel-buildfarm)
* [BuildGrid](https://gitlab.com/BuildGrid/buildgrid)
* [issue #4558](https://github.com/bazelbuild/bazel/issues/4558)
* [Application Authentication](https://cloud.google.com/docs/authentication/production)
* [NativeLink](https://github.com/TraceMachina/nativelink)
# Configuring Bazel CI to Test Rules for Remote Execution
Source: https://bazel.build/remote/ci
This page is for owners and maintainers of Bazel rule repositories. It
describes how to configure the Bazel Continuous Integration (CI) system for
your repository to test your rules for compatibility against a remote execution
scenario. The instructions on this page apply to projects stored in
GitHub repositories.
## Prerequisites
Before completing the steps on this page, ensure the following:
* Your GitHub repository is part of the
[Bazel GitHub organization](https://github.com/bazelbuild).
* You have configured Buildkite for your repository as described in
[Bazel Continuous Integration](https://github.com/bazelbuild/continuous-integration/tree/master/buildkite).
## Setting up the Bazel CI for testing
1. In your `.bazelci/presubmit.yml` file, do the following:
a. Add a config named `rbe_ubuntu1604`.
b. In the `rbe_ubuntu1604` config, add the build and test targets you want to test against remote execution.
2. Add the[`bazel-toolchains`](https://github.com/bazelbuild/bazel-toolchains)
GitHub repository to your `WORKSPACE` file, pinned to the
[latest release](https://releases.bazel.build/bazel-toolchains.html). Also
add an `rbe_autoconfig` target with name `buildkite_config`. This example
creates toolchain configuration for remote execution with BuildKite CI
for `rbe_ubuntu1604`.
```posix-terminal theme={null}
load("@bazel_toolchains//rules:rbe_repo.bzl", "rbe_autoconfig")
rbe_autoconfig(name = "buildkite_config")
```
3. Send a pull request with your changes to the `presubmit.yml` file. (See
[example pull request](https://github.com/bazelbuild/rules_rust/commit/db141526d89d00748404856524cedd7db8939c35).)
4. To view build results, click **Details** for the RBE (Ubuntu
16.04) pull request check in GitHub, as shown in the figure below. This link
becomes available after the pull request has been merged and the CI tests
have run. (See
[example results](https://source.cloud.google.com/results/invocations/375e325c-0a05-47af-87bd-fed1363e0333).)
5. (Optional) Set the **bazel test (RBE (Ubuntu 16.04))** check as a test
required to pass before merging in your branch protection rule. The setting
is located in GitHub in **Settings > Branches > Branch protection rules**,
as shown in the following figure.
## Troubleshooting failed builds and tests
If your build or tests fail, it's likely due to the following:
* **Required build or test tools are not installed in the default container.**
Builds using the `rbe_ubuntu1604` config run by default inside an
[`rbe-ubuntu16-04`](https://console.cloud.google.com/marketplace/details/google/rbe-ubuntu16-04)
container, which includes tools common to many Bazel builds. However, if
your rules require tools not present in the default container, you must
create a custom container based on the
[`rbe-ubuntu16-04`](https://console.cloud.google.com/marketplace/details/google/rbe-ubuntu16-04)
container and include those tools as described later.
* **Build or test targets are using rules that are incompatible with remote
execution.** See
[Adapting Bazel Rules for Remote Execution](/remote/rules) for
details about compatibility with remote execution.
## Using a custom container in the rbe\_ubuntu1604 CI config
The `rbe-ubuntu16-04` container is publicly available at the following URL:
```
http://gcr.io/cloud-marketplace/google/rbe-ubuntu16-04
```
You can pull it directly from Container Registry or build it from source. The
next sections describe both options.
Before you begin, make sure you have installed `gcloud`, `docker`, and `git`.
If you are building the container from source, you must also install the latest
version of Bazel.
### Pulling the rbe-ubuntu16-04 from Container Registry
To pull the `rbe-ubuntu16-04` container from Container Registry, run the
following command:
```posix-terminal theme={null}
gcloud docker -- pull gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:sha256-checksum
```
Replace sha256-checksum with the SHA256 checksum value for
[the latest container](https://console.cloud.google.com/gcr/images/cloud-marketplace/GLOBAL/google/rbe-ubuntu16-04).
### Building the rbe-ubuntu16-04 container from source
To build the `rbe-ubuntu16-04` container from source, do the following:
1. Clone the `bazel-toolchains` repository:
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/bazel-toolchains
```
2. Set up toolchain container targets and build the container as explained in
[Toolchain Containers](https://github.com/bazelbuild/bazel-toolchains/tree/master/container).
3. Pull the freshly built container:
```posix-terminal theme={null}
```
gcloud docker -- pull gcr.io/project-id/custom-container-namesha256-checksum
````
Running the custom container
To run the custom container, do one of the following:
* If you pulled the container from Container Registry, run the following
command:
```posix-terminal
docker run -it gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:sha256-checksum/bin/bash
````
Replace `sha256-checksum` with the SHA256 checksum value for the
[latest container](https://console.cloud.google.com/gcr/images/cloud-marketplace/GLOBAL/google/rbe-ubuntu16-04).
* If you built the container from source, run the following command:
```posix-terminal theme={null}
docker run -it gcr.io/project-id/custom-container-name@sha256:sha256sum /bin/bash
```
### Adding resources to the custom container
Use a [`Dockerfile`](https://docs.docker.com/engine/reference/builder/) or
[`rules_docker`](https://github.com/bazelbuild/rules_docker) to add resources or
alternate versions of the original resources to the `rbe-ubuntu16-04` container.
If you are new to Docker, read the following:
* [Docker for beginners](https://github.com/docker/labs/tree/master/beginner)
* [Docker Samples](https://docs.docker.com/samples/)
For example, the following `Dockerfile` snippet installs `my_tool_package`:
```
FROM gcr.io/cloud-marketplace/google/rbe-ubuntu16-04@sha256:sha256-checksum
RUN apt-get update && yes | apt-get install -y my_tool_package
```
### Pushing the custom container to Container Registry
Once you have customized the container, build the container image and push it to
Container Registry as follows:
1. Build the container image:
```posix-terminal theme={null}
docker build -t custom-container-name.
docker tag custom-container-name gcr.io/project-id/custom-container-name
```
2. Push the container image to Container Registry:
```posix-terminal theme={null}
gcloud docker -- push gcr.io/project-id/custom-container-name
```
3. Navigate to the following URL to verify the container has been pushed:
[https://console.cloud.google.com/gcr/images/](https://console.cloud.google.com/gcr/images/)project-id/GLOBAL/custom-container-name
4. Take note of the SHA256 checksum of your custom container. You will need to
provide it in your build platform definition later.
5. Configure the container for public access as described in publicly
accessible as explained in
[Serving images publicly](https://cloud.google.com/container-registry/docs/access-control#serving_images_publicly).
For more information, see
[Pushing and Pulling Images](https://cloud.google.com/container-registry/docs/pushing-and-pulling).
### Specifying the build platform definition
You must include a [Bazel platform](/extending/platforms) configuration in your
custom toolchain configuration, which allows Bazel to select a toolchain
appropriate to the desired hardware/software platform. To generate
automatically a valid platform, you can add to your `WORKSPACE` an
`rbe_autoconfig` target with name `buildkite_config` which includes additional
attrs to select your custom container. For details on this setup, read
the up-to-date documentation for [`rbe_autoconfig`](https://github.com/bazelbuild/bazel-toolchains/blob/master/rules/rbe_repo.bzl).
# Creating Persistent Workers
Source: https://bazel.build/remote/creating
[Persistent workers](/remote/persistent) can make your build faster. If
you have repeated actions in your build that have a high startup cost or would
benefit from cross-action caching, you may want to implement your own persistent
worker to perform these actions.
The Bazel server communicates with the worker using `stdin`/`stdout`. It
supports the use of protocol buffers or JSON strings.
The worker implementation has two parts:
* The [worker](#making-worker).
* The [rule that uses the worker](#rule-uses-worker).
## Making the worker
A persistent worker upholds a few requirements:
* It reads
[WorkRequests](https://github.com/bazelbuild/bazel/blob/54a547f30fd582933889b961df1d6e37a3e33d85/src/main/protobuf/worker_protocol.proto#L36)
from its `stdin`.
* It writes
[WorkResponses](https://github.com/bazelbuild/bazel/blob/54a547f30fd582933889b961df1d6e37a3e33d85/src/main/protobuf/worker_protocol.proto#L77)
(and only `WorkResponse`s) to its `stdout`.
* It accepts the `--persistent_worker` flag. The wrapper must recognize the
`--persistent_worker` command-line flag and only make itself persistent if
that flag is passed, otherwise it must do a one-shot compilation and exit.
If your program upholds these requirements, it can be used as a persistent
worker!
### Work requests
A `WorkRequest` contains a list of arguments to the worker, a list of
path-digest pairs representing the inputs the worker can access (this isn’t
enforced, but you can use this info for caching), and a request id, which is 0
for singleplex workers.
NOTE: While the protocol buffer specification uses "snake case" (`request_id`),
the JSON protocol uses "camel case" (`requestId`). This document uses camel case
in the JSON examples, but snake case when talking about the field regardless of
protocol.
```json theme={null}
{
"arguments" : ["--some_argument"],
"inputs" : [
{ "path": "/path/to/my/file/1", "digest": "fdk3e2ml23d"},
{ "path": "/path/to/my/file/2", "digest": "1fwqd4qdd" }
],
"requestId" : 12
}
```
The optional `verbosity` field can be used to request extra debugging output
from the worker. It is entirely up to the worker what and how to output. Higher
values indicate more verbose output. Passing the `--worker_verbose` flag to
Bazel sets the `verbosity` field to 10, but smaller or larger values can be used
manually for different amounts of output.
The optional `sandbox_dir` field is used only by workers that support
[multiplex sandboxing](/remote/multiplex).
### Work responses
A `WorkResponse` contains a request id, a zero or nonzero exit code, and an
output message describing any errors encountered in processing or executing
the request. A worker should capture the `stdout` and `stderr` of any tool it
calls and report them through the `WorkResponse`. Writing it to the `stdout` of
the worker process is unsafe, as it will interfere with the worker protocol.
Writing it to the `stderr` of the worker process is safe, but the result is
collected in a per-worker log file instead of ascribed to individual actions.
```json theme={null}
{
"exitCode" : 1,
"output" : "Action failed with the following message:\nCould not find input
file \"/path/to/my/file/1\"",
"requestId" : 12
}
```
As per the norm for protobufs, all fields are optional. However, Bazel requires
the `WorkRequest` and the corresponding `WorkResponse`, to have the same request
id, so the request id must be specified if it is nonzero. This is a valid
`WorkResponse`.
```json theme={null}
{
"requestId" : 12,
}
```
A `request_id` of 0 indicates a "singleplex" request, used when this request
cannot be processed in parallel with other requests. The server guarantees that
a given worker receives requests with either only `request_id` 0 or only
`request_id` greater than zero. Singleplex requests are sent in serial, for
example if the server doesn't send another request until it has received a
response (except for cancel requests, see below).
**Notes**
* Each protocol buffer is preceded by its length in `varint` format (see
[`MessageLite.writeDelimitedTo()`](https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite.html#writeDelimitedTo-java.io.OutputStream-).
* JSON requests and responses are not preceded by a size indicator.
* JSON requests uphold the same structure as the protobuf, but use standard
JSON and use camel case for all field names.
* In order to maintain the same backward and forward compatibility properties
as protobuf, JSON workers must tolerate unknown fields in these messages,
and use the protobuf defaults for missing values.
* Bazel stores requests as protobufs and converts them to JSON using
[protobuf's JSON format](https://cs.opensource.google/protobuf/protobuf/+/master:java/util/src/main/java/com/google/protobuf/util/JsonFormat.java)
### Cancellation
Workers can optionally allow work requests to be cancelled before they finish.
This is particularly useful in connection with dynamic execution, where local
execution can regularly be interrupted by a faster remote execution. To allow
cancellation, add `supports-worker-cancellation: 1` to the
`execution-requirements` field (see below) and set the
`--experimental_worker_cancellation` flag.
A **cancel request** is a `WorkRequest` with the `cancel` field set (and
similarly a **cancel response** is a `WorkResponse` with the `was_cancelled`
field set). The only other field that must be in a cancel request or cancel
response is `request_id`, indicating which request to cancel. The `request_id`
field will be 0 for singleplex workers or the non-0 `request_id` of a previously
sent `WorkRequest` for multiplex workers. The server may send cancel requests
for requests that the worker has already responded to, in which case the cancel
request must be ignored.
Each non-cancel `WorkRequest` message must be answered exactly once, whether or
not it was cancelled. Once the server has sent a cancel request, the worker may
respond with a `WorkResponse` with the `request_id` set and the `was_cancelled`
field set to true. Sending a regular `WorkResponse` is also accepted, but the
`output` and `exit_code` fields will be ignored.
Once a response has been sent for a `WorkRequest`, the worker must not touch the
files in its working directory. The server is free to clean up the files,
including temporary files.
## Making the rule that uses the worker
You'll also need to create a rule that generates actions to be performed by the
worker. Making a Starlark rule that uses a worker is just like
[creating any other rule](https://github.com/bazelbuild/examples/tree/master/rules).
In addition, the rule needs to contain a reference to the worker itself, and
there are some requirements for the actions it produces.
### Referring to the worker
The rule that uses the worker needs to contain a field that refers to the worker
itself, so you'll need to create an instance of a `\*\_binary` rule to define
your worker. If your worker is called `MyWorker.Java`, this might be the
associated rule:
```python theme={null}
java_binary(
name = "worker",
srcs = ["MyWorker.Java"],
)
```
This creates the "worker" label, which refers to the worker binary. You'll then
define a rule that *uses* the worker. This rule should define an attribute that
refers to the worker binary.
If the worker binary you built is in a package named "work", which is at the top
level of the build, this might be the attribute definition:
```python theme={null}
"worker": attr.label(
default = Label("//work:worker"),
executable = True,
cfg = "exec",
)
```
`cfg = "exec"` indicates that the worker should be built to run on your
execution platform rather than on the target platform (i.e., the worker is used
as tool during the build).
### Work action requirements
The rule that uses the worker creates actions for the worker to perform. These
actions have a couple of requirements.
* The *"arguments"* field. This takes a list of strings, all but the last of
which are arguments passed to the worker upon startup. The last element in
the "arguments" list is a `flag-file` (@-preceded) argument. Workers read
the arguments from the specified flagfile on a per-WorkRequest basis. Your
rule can write non-startup arguments for the worker to this flagfile.
* The *"execution-requirements"* field, which takes a dictionary containing
`"supports-workers" : "1"`, `"supports-multiplex-workers" : "1"`, or both.
The "arguments" and "execution-requirements" fields are required for all
actions sent to workers. Additionally, actions that should be executed by
JSON workers need to include `"requires-worker-protocol" : "json"` in the
execution requirements field. `"requires-worker-protocol" : "proto"` is also
a valid execution requirement, though it’s not required for proto workers,
since they are the default.
You can also set a `worker-key-mnemonic` in the execution requirements. This
may be useful if you're reusing the executable for multiple action types and
want to distinguish actions by this worker.
* Temporary files generated in the course of the action should be saved to the
worker's directory. This enables sandboxing.
Note: To pass an argument starting with a literal `@`, start the argument with
`@@` instead. If an argument is also an external repository label, it will not
be considered a flagfile argument.
Assuming a rule definition with "worker" attribute described above, in addition
to a "srcs" attribute representing the inputs, an "output" attribute
representing the outputs, and an "args" attribute representing the worker
startup args, the call to `ctx.actions.run` might be:
```python theme={null}
ctx.actions.run(
inputs=ctx.files.srcs,
outputs=[ctx.outputs.output],
executable=ctx.executable.worker,
mnemonic="someMnemonic",
execution_requirements={
"supports-workers" : "1",
"requires-worker-protocol" : "json"},
arguments=ctx.attr.args + ["@flagfile"]
)
```
For another example, see
[Implementing persistent workers](/remote/persistent#implementation).
## Examples
The Bazel code base uses
[Java compiler workers](https://github.com/bazelbuild/bazel/blob/a4251eab6988d6cf4f5e35681fbe2c1b0abe48ef/src/java_tools/buildjar/java/com/google/devtools/build/buildjar/BazelJavaBuilder.java),
in addition to an
[example JSON worker](https://github.com/bazelbuild/bazel/blob/c65f768fec9889bbf1ee934c61d0dc061ea54ca2/src/test/java/com/google/devtools/build/lib/worker/ExampleWorker.java)
that is used in our integration tests.
You can use their
[scaffolding](https://github.com/bazelbuild/bazel/blob/a4251eab6988d6cf4f5e35681fbe2c1b0abe48ef/src/main/java/com/google/devtools/build/lib/worker/WorkRequestHandler.java)
to make any Java-based tool into a worker by passing in the correct callback.
For an example of a rule that uses a worker, take a look at Bazel's
[worker integration test](https://github.com/bazelbuild/bazel/blob/22b4dbcaf05756d506de346728db3846da56b775/src/test/shell/integration/bazel_worker_test.sh#L106).
External contributors have implemented workers in a variety of languages; take a
look at
[Polyglot implementations of Bazel persistent workers](https://github.com/Ubehebe/bazel-worker-examples).
You can
[find many more examples on GitHub](https://github.com/search?q=bazel+workrequest\&type=Code)!
# Dynamic Execution
Source: https://bazel.build/remote/dynamic
**Dynamic execution** is a feature in Bazel where local and remote execution of
the same action are started in parallel, using the output from the first branch
that finishes, cancelling the other branch. It combines the execution power
and/or large shared cache of a remote build system with the low latency of local
execution, providing the best of both worlds for clean and incremental builds
alike.
This page describes how to enable, tune, and debug dynamic execution. If you
have both local and remote execution set up and are trying to adjust Bazel
settings for better performance, this page is for you. If you don't already have
remote execution set up, go to the Bazel [Remote Execution Overview](/remote/rbe) first.
## Enabling dynamic execution?
The dynamic execution module is part of Bazel, but to make use of dynamic
execution, you must already be able to compile both locally and remotely from
the same Bazel setup.
To enable the dynamic execution module, pass the `--internal_spawn_scheduler`
flag to Bazel. This adds a new execution strategy called `dynamic`. You can now
use this as your strategy for the mnemonics you want to run dynamically, such as
`--strategy=Javac=dynamic`. See the next section for how to pick which mnemonics
to enable dynamic execution for.
For any mnemonic using the dynamic strategy, the remote execution strategies are
taken from the `--dynamic_remote_strategy` flag, and local strategies from the
`--dynamic_local_strategy` flag. Passing
`--dynamic_local_strategy=worker,sandboxed` sets the default for the local
branch of dynamic execution to try with workers or sandboxed execution in that
order. Passing `--dynamic_local_strategy=Javac=worker` overrides the default for
the Javac mnemonic only. The remote version works the same way. Both flags can
be specified multiple times. If an action cannot be executed locally, it is
executed remotely as normal, and vice-versa.
If your remote system has a cache, the `--dynamic_local_execution_delay` flag
adds a delay in milliseconds to the local execution after the remote system has
indicated a cache hit. This avoids running local execution when more cache hits
are likely. The default value is 1000ms, but should be tuned to being just a bit
longer than cache hits usually take. The actual time depends both on the remote
system and on how long a round-trip takes. Usually, the value will be the same
for all users of a given remote system, unless some of them are far enough away
to add roundtrip latency. You can use the [Bazel profiling features](/rules/performance#performance-profiling) to look at how long typical
cache hits take.
Dynamic execution can be used with local sandboxed strategy as well as with
[persistent workers](/remote/persistent). Persistent workers will automatically
run with sandboxing when used with dynamic execution, and cannot use [multiplex workers](/remote/multiplex). On Darwin and Windows systems, the sandboxed
strategy can be slow; you can pass `--reuse_sandbox_directories` to reduce
overhead of creating sandboxes on these systems.
Dynamic execution can also run with the `standalone` strategy, though since the
`standalone` strategy must take the output lock when it starts executing, it
effectively blocks the remote strategy from finishing first. The
`--experimental_local_lockfree_output` flag enables a way around this problem by
allowing the local execution to write directly to the output, but be aborted by
the remote execution, should that finish first.
If one of the branches of dynamic execution finishes first but is a failure, the
entire action fails. This is an intentional choice to prevent differences
between local and remote execution from going unnoticed.
For more background on how dynamic execution and its locking works, see Julio
Merino's excellent [blog posts](https://jmmv.dev/series/bazel-dynamic-execution/)
## When should I use dynamic execution?
Dynamic execution requires some form of [remote execution system](/remote/rbe).
It is not currently possible to use a cache-only remote system, as a cache miss
would be considered a failed action.
Not all types of actions are well suited for remote execution. The best
candidates are those that are inherently faster locally, for instance through
the use of [persistent workers](/remote/persistent), or those that run fast
enough that the overhead of remote execution dominates execution time. Since
each locally executed action locks some amount of CPU and memory resources,
running actions that don't fall into those categories merely delays execution
for those that do.
As of release
[5.0.0-pre.20210708.4](https://github.com/bazelbuild/bazel/releases/tag/5.0.0-pre.20210708.4),
[performance profiling](/rules/performance#performance-profiling) contains data
about worker execution, including time spent finishing a work request after
losing a dynamic execution race. If you see dynamic execution worker threads
spending significant time acquiring resources, or a lot of time in the
`async-worker-finish`, you may have some slow local actions delaying the worker
threads.
In the profile above, which uses 8 Javac workers, we see many Javac workers
having lost the races and finishing their work on the `async-worker-finish`
threads. This was caused by a non-worker mnemonic taking enough resources to
delay the workers.
When only Javac is run with dynamic execution, only about half of the started
workers end up losing the race after starting their work.
The previously recommended `--experimental_spawn_scheduler` flag is deprecated.
It turns on dynamic execution and sets `dynamic` as the default strategy for all
mnemonics, which would often lead to these kinds of problems.
## Performance
The dynamic execution approach assumes there are enough resources available
locally and remotely that it's worth spending some extra resources to improve
overall performance. But excessive resource usage may slow down Bazel itself or
the machine it runs on, or put unexpected pressure on a remote system. There are
several options for changing the behaviour of dynamic execution:
`--dynamic_local_execution_delay` delays the start of a local branch by a number
of milliseconds after the remote branch has started, but only if there has been
a remote cache hit during the current build. This makes builds that benefit
from remote caching not waste local resources when it is likely that most
outputs can be found in the cache. Depending on the quality of the cache,
reducing this might improve build speeds, at the cost of using more local
resources.
`--experimental_dynamic_local_load_factor` is an experimental advanced resource
management option. It takes a value from 0 to 1, 0 turning off this feature.
When set to a value above 0, Bazel adjusts the number of
locally scheduled actions when many actions waiting to
be scheduled. Setting it to 1 allows as many actions to be scheduled as there
are CPUs available (as per `--local_resources`). Lower values set the number
of actions scheduled to correspondingly fewer as higher numbers of actions are
available to run. This may sound counter-intuitive, but with a good remote
system, local execution does not help much when many actions are being run, and
the local CPU is better spent managing remote actions.
`--experimental_dynamic_slow_remote_time` prioritizes starting local branches
when the remote branch has been running for at least this long. Normally the
most recently scheduled action gets priority, as it has the greatest chance of
winning the race, but if the remote system sometimes hangs or takes extra long,
this can get a build to move along. This is not enabled by default, because it
could hide issues with the remote system that should rather be fixed. Make sure
to monitor your remote system performance if you enable this option.
`--experimental_dynamic_ignore_local_signals` can be used to let the remote
branch take over when a local spawn exits due to a given signal. This is
is mainly useful together with worker resource limits (see
[`--experimental_worker_memory_limit_mb`](https://bazel.build/reference/command-line-reference#flag--experimental_worker_memory_limit_mb),
[`--experimental_worker_sandbox_hardening`](https://bazel.build/reference/command-line-reference#flag--experimental_worker_sandbox_hardening),
and
[`--experimental_sandbox_memory_limit_mb`)](https://bazel.build/reference/command-line-reference#flag--experimental_sandbox_memory_limit_mb)),
where worker processes may be killed when they use too many resources.
The [JSON trace profile](/advanced/performance/json-trace-profile) contains a
number of performance-related graphs that can help identify ways to improve the
trade-off of performance and resource usage.
## Troubleshooting
Problems with dynamic execution can be subtle and hard to debug, as they can
manifest only under some specific combinations of local and remote execution.
The `--debug_spawn_scheduler` adds extra output from the dynamic execution
system that can help debug these problems. You can also adjust the
`--dynamic_local_execution_delay` flag and number of remote vs. local jobs to
make it easier to reproduce the problems.
If you are experiencing problems with dynamic execution using the `standalone`
strategy, try running without `--experimental_local_lockfree_output`, or run
your local actions sandboxed. This may slow down your build a bit (see above if
you're on Mac or Windows), but removes some possible causes for failures.
# Multiplex Workers (Experimental Feature)
Source: https://bazel.build/remote/multiplex
This page describes multiplex workers, how to write multiplex-compatible
rules, and workarounds for certain limitations.
Caution: Experimental features are subject to change at any time.
*Multiplex workers* allow Bazel to handle multiple requests with a single worker
process. For multi-threaded workers, Bazel can use fewer resources to
achieve the same, or better performance. For example, instead of having one
worker process per worker, Bazel can have four multiplexed workers talking to
the same worker process, which can then handle requests in parallel. For
languages like Java and Scala, this saves JVM warm-up time and JIT compilation
time, and in general it allows using one shared cache between all workers of
the same type.
## Overview
There are two layers between the Bazel server and the worker process. For certain
mnemonics that can run processes in parallel, Bazel gets a `WorkerProxy` from
the worker pool. The `WorkerProxy` forwards requests to the worker process
sequentially along with a `request_id`, the worker process processes the request
and sends responses to the `WorkerMultiplexer`. When the `WorkerMultiplexer`
receives a response, it parses the `request_id` and then forwards the responses
back to the correct `WorkerProxy`. Just as with non-multiplexed workers, all
communication is done over standard in/out, but the tool cannot just use
`stderr` for user-visible output ([see below](#output)).
Each worker has a key. Bazel uses the key's hash code (composed of environment
variables, the execution root, and the mnemonic) to determine which
`WorkerMultiplexer` to use. `WorkerProxy`s communicate with the same
`WorkerMultiplexer` if they have the same hash code. Therefore, assuming
environment variables and the execution root are the same in a single Bazel
invocation, each unique mnemonic can only have one `WorkerMultiplexer` and one
worker process. The total number of workers, including regular workers and
`WorkerProxy`s, is still limited by `--worker_max_instances`.
## Writing multiplex-compatible rules
The rule's worker process should be multi-threaded to take advantage of
multiplex workers. Protobuf allows a ruleset to parse a single request even
though there might be multiple requests piling up in the stream. Whenever the
worker process parses a request from the stream, it should handle the request in
a new thread. Because different thread could complete and write to the stream at
the same time, the worker process needs to make sure the responses are written
atomically (messages don't overlap). Responses must contain the
`request_id` of the request they're handling.
### Handling multiplex output
Multiplex workers need to be more careful about handling their output than
singleplex workers. Anything sent to `stderr` will go into a single log file
shared among all `WorkerProxy`s of the same type,
randomly interleaved between concurrent requests. While redirecting `stdout`
into `stderr` is a good idea, do not collect that output into the `output`
field of `WorkResponse`, as that could show the user mangled pieces of output.
If your tool only sends user-oriented output to `stdout` or `stderr`, you will
need to change that behaviour before you can enable multiplex workers.
## Enabling multiplex workers
Multiplex workers are not enabled by default. A ruleset can turn on multiplex
workers by using the `supports-multiplex-workers` tag in the
`execution_requirements` of an action (just like the `supports-workers` tag
enables regular workers). As is the case when using regular workers, a worker
strategy needs to be specified, either at the ruleset level (for example,
`--strategy=[some_mnemonic]=worker`) or generally at the strategy level (for
example, `--dynamic_local_strategy=worker,standalone`.) No additional flags are
necessary, and `supports-multiplex-workers` takes precedence over
`supports-workers`, if both are set. You can turn off multiplex workers
globally by passing `--noworker_multiplex`.
A ruleset is encouraged to use multiplex workers if possible, to reduce memory
pressure and improve performance. However, multiplex workers are not currently
compatible with [dynamic execution](/remote/dynamic) unless they
implement multiplex sandboxing. Attempting to run non-sandboxed multiplex
workers with dynamic execution will silently use sandboxed
singleplex workers instead.
## Multiplex sandboxing
Multiplex workers can be sandboxed by adding explicit support for it in the
worker implementations. While singleplex worker sandboxing can be done by
running each worker process in its own sandbox, multiplex workers share the
process working directory between multiple parallel requests. To allow
sandboxing of multiplex workers, the worker must support reading from and
writing to a subdirectory specified in each request, instead of directly in
its working directory.
To support multiplex sandboxing, the worker must use the `sandbox_dir` field
from the `WorkRequest` and use that as a prefix for all file reads and writes.
While the `arguments` and `inputs` fields remain unchanged from an unsandboxed
request, the actual inputs are relative to the `sandbox_dir`. The worker must
translate file paths found in `arguments` and `inputs` to read from this
modified path, and must also write all outputs relative to the `sandbox_dir`.
This includes paths such as '.', as well as paths found in files specified
in the arguments (such as ["argfile"](https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javac.html#commandlineargfile) arguments).
Once a worker supports multiplex sandboxing, the ruleset can declare this
support by adding `supports-multiplex-sandboxing` to the
`execution_requirements` of an action. Bazel will then use multiplex sandboxing
if the `--experimental_worker_multiplex_sandboxing` flag is passed, or if
the worker is used with dynamic execution.
The worker files of a sandboxed multiplex worker are still relative to the
working directory of the worker process. Thus, if a file is
used both for running the worker and as an input, it must be specified both as
an input in the flagfile argument as well as in `tools`, `executable`, or
`runfiles`.
# Output Directory Layout
Source: https://bazel.build/remote/output-directories
This page covers requirements and layout for output directories.
## Requirements
Requirements for an output directory layout:
* Doesn't collide if multiple users are building on the same box.
* Supports building in multiple workspaces at the same time.
* Supports building for multiple target configurations in the same workspace.
* Doesn't collide with any other tools.
* Is easy to access.
* Is easy to clean, even selectively.
* Is unambiguous, even if the user relies on symbolic links when changing into
their client directory.
* All the build state per user should be underneath one directory ("I'd like to
clean all the .o files from all my clients.")
## Current layout
The solution that's currently implemented:
* Bazel must be invoked from a directory containing a repository boundary file,
or a subdirectory thereof. In other words, Bazel must be invoked from inside a
[repository](/external/overview#repository). Otherwise, an error is
reported.
* The *outputRoot* directory defaults to \~/.cache/bazel on Linux,
`~/Library/Caches/bazel` on macOS (when using Bazel 9 and newer),
and on Windows it defaults to `%HOME%` if set, else `%USERPROFILE%`
if set, else the result of calling `SHGetKnownFolderPath()` with the
`FOLDERID_Profile` flag set. If the environment variable `$XDG_CACHE_HOME`
is set on Linux, macOS, or Windows, the value `${XDG_CACHE_HOME}/bazel` will
override the default. If the environment variable `$TEST_TMPDIR` is set,
as in a test of Bazel itself, then that value overrides any defaults.
* Note that Bazel 8.x and earlier on macOS used `/private/var/tmp` as *outputRoot*,
and ignored `$XDG_CACHE_HOME`.
* The Bazel user's build state is located beneath `outputRoot/_bazel_$USER`.
This is called the *outputUserRoot* directory.
* Beneath the `outputUserRoot` directory there is an `install` directory, and in
it is an `installBase` directory whose name is the MD5 hash of the Bazel
installation manifest.
* Beneath the `outputUserRoot` directory, an `outputBase` directory
is also created whose name is the MD5 hash of the path of the workspace
root. So, for example, if Bazel is running in the workspace root
`/home/user/src/my-project` (or in a directory symlinked to that one), then
an output base directory is created called:
`/home/user/.cache/bazel/_bazel_user/7ffd56a6e4cb724ea575aba15733d113`. You
can also run `echo -n $(pwd) | md5sum` in the workspace root to get the MD5.
* You can use Bazel's `--output_base` startup option to override the default
output base directory. For example,
`bazel --output_base=/tmp/bazel/output build x/y:z`.
* You can also use Bazel's `--output_user_root` startup option to override the
default install base and output base directories. For example:
`bazel --output_user_root=/tmp/bazel build x/y:z`.
The symlinks for "bazel-\", "bazel-out", "bazel-testlogs",
and "bazel-bin" are put in the workspace directory; these symlinks point to some
directories inside a target-specific directory inside the output directory.
These symlinks are only for the user's convenience, as Bazel itself does not
use them. Also, this is done only if the workspace root is writable.
## Layout diagram
The directories are laid out as follows:
```
<workspace-name>/ <== The workspace root
bazel-my-project => <..._main> <== Symlink to execRoot
bazel-out => <...bazel-out> <== Convenience symlink to outputPath
bazel-bin => <...bin> <== Convenience symlink to most recent written bin dir $(BINDIR)
bazel-testlogs => <...testlogs> <== Convenience symlink to the test logs directory
/home/user/.cache/bazel/ <== Root for all Bazel output on a machine: outputRoot
_bazel_$USER/ <== Top level directory for a given user depends on the user name:
outputUserRoot
install/
fba9a2c87ee9589d72889caf082f1029/ <== Hash of the Bazel install manifest: installBase
A-server.jar <== The main Bazel server Java application, unpacked
from the data section of the bazel executable on first run.
linux-sandbox <== Sandboxing helper binary (platform-specific).
process-wrapper <== Process wrapper binary for action execution.
embedded_tools/ <== Contains the bundled JDK, build tool sources,
and other resources needed by the server.
7ffd56a6e4cb724ea575aba15733d113/ <== Hash of the client's workspace root (such as
/home/user/src/my-project): outputBase
action_cache/ <== Action cache directory hierarchy
This contains the persistent record of the file
metadata (timestamps, and perhaps eventually also MD5
sums) used by the FilesystemValueChecker.
command.log <== A copy of the stdout/stderr output from the most
recent bazel command.
external/ <== The directory that remote repositories are
downloaded/symlinked into.
server/ <== The Bazel server puts all server-related files here
(such as the server PID, the TCP command port,
request/response cookies, and JVM logs).
jvm.out <== The debugging output for the server.
execroot/ <== The working directory for all actions. For special
cases such as sandboxing and remote execution, the
actions run in a directory that mimics execroot.
Implementation details, such as where the directories
are created, are intentionally hidden from the action.
Every action can access its inputs and outputs relative
to the execroot directory.
_main/ <== Working tree for the Bazel build & root of symlink forest: execRoot
_bin/ <== Helper tools are linked from or copied to here.
bazel-out/ <== All actual output of the build is under here: outputPath
_tmp/actions/ <== Action output directory. This contains a file with the
stdout/stderr for every action from the most recent
bazel run that produced output.
k8-fastbuild/ <== One subdirectory per unique target BuildConfiguration instance;
named by a mnemonic encoding the CPU and compilation mode
(such as k8-fastbuild, k8-opt, or k8-dbg). Configurations
with Starlark transitions append an ST-hash suffix
(such as k8-fastbuild-ST-abc123).
bin/ <== Bazel outputs binaries for target configuration here: $(BINDIR)
foo/bar/_objs/baz/ <== Object files for a cc_* rule named //foo/bar:baz
foo/bar/baz1.o <== Object files from source //foo/bar:baz1.cc
other_package/other.o <== Object files from source //other_package:other.cc
foo/bar/baz <== foo/bar/baz might be the artifact generated by a cc_binary named
//foo/bar:baz
foo/bar/baz.runfiles/ <== The runfiles symlink farm for the //foo/bar:baz executable.
MANIFEST
_main/
...
testlogs/ <== Bazel internal test runner puts test log files here
foo/bartest.log such as foo/bar.log might be an output of the //foo:bartest test with
foo/bartest.status foo/bartest.status containing exit status of the test (such as
PASSED or FAILED (Exit 1), etc)
k8-opt-exec/ <== BuildConfiguration for the exec platform, used for
building prerequisite tools (such as the Protocol Compiler)
that will be used in later stages of the build.
<packages>/ <== Packages referenced in the build appear as if under a regular workspace
```
The layout of the \*.runfiles directories is documented in more detail in the places pointed to by RunfilesSupport.
## `bazel clean`
`bazel clean` clears the on-disk action cache and then removes the entire
`execroot` directory (which contains the symlink forest and all build
outputs). It also removes the convenience symlinks from the workspace
directory. The `--expunge` option will clean the entire outputBase.
# Persistent Workers
Source: https://bazel.build/remote/persistent
This page covers how to use persistent workers, the benefits, requirements, and
how workers affect sandboxing.
A persistent worker is a long-running process started by the Bazel server, which
functions as a *wrapper* around the actual *tool* (typically a compiler), or is
the *tool* itself. In order to benefit from persistent workers, the tool must
support doing a sequence of compilations, and the wrapper needs to translate
between the tool's API and the request/response format described below. The same
worker might be called with and without the `--persistent_worker` flag in the
same build, and is responsible for appropriately starting and talking to the
tool, as well as shutting down workers on exit. Each worker instance is assigned
(but not chrooted to) a separate working directory under
`/bazel-workers`.
Using persistent workers is an
[execution strategy](/docs/user-manual#execution-strategy) that decreases
start-up overhead, allows more JIT compilation, and enables caching of for
example the abstract syntax trees in the action execution. This strategy
achieves these improvements by sending multiple requests to a long-running
process.
Persistent workers are implemented for multiple languages, including Java,
[Scala](https://github.com/bazelbuild/rules_scala),
[Kotlin](https://github.com/bazelbuild/rules_kotlin), and more.
Programs using a NodeJS runtime can use the
[@bazel/worker](https://www.npmjs.com/package/@bazel/worker) helper library to
implement the worker protocol.
## Using persistent workers
[Bazel 0.27 and higher](https://blog.bazel.build/2019/06/19/list-strategy.html)
uses persistent workers by default when executing builds, though remote
execution takes precedence. For actions that do not support persistent workers,
Bazel falls back to starting a tool instance for each action. You can explicitly
set your build to use persistent workers by setting the `worker`
[strategy](/docs/user-manual#execution-strategy) for the applicable tool
mnemonics. As a best practice, this example includes specifying `local` as a
fallback to the `worker` strategy:
```posix-terminal theme={null}
bazel build //my:target --strategy=Javac=worker,local
```
Using the workers strategy instead of the local strategy can boost compilation
speed significantly, depending on implementation. For Java, builds can be 2–4
times faster, sometimes more for incremental compilation. Compiling Bazel is
about 2.5 times as fast with workers. For more details, see the
"[Choosing number of workers](#number-of-workers)" section.
If you also have a remote build environment that matches your local build
environment, you can use the experimental
[*dynamic* strategy](https://blog.bazel.build/2019/02/01/dynamic-spawn-scheduler.html),
which races a remote execution and a worker execution. To enable the dynamic
strategy, pass the
[--experimental\_spawn\_scheduler](/reference/command-line-reference#flag--experimental_spawn_scheduler)
flag. This strategy automatically enables workers, so there is no need to
specify the `worker` strategy, but you can still use `local` or `sandboxed` as
fallbacks.
## Choosing number of workers
The default number of worker instances per mnemonic is 4, but can be adjusted
with the
[`worker_max_instances`](/reference/command-line-reference#flag--worker_max_instances)
flag. There is a trade-off between making good use of the available CPUs and the
amount of JIT compilation and cache hits you get. With more workers, more
targets will pay start-up costs of running non-JITted code and hitting cold
caches. If you have a small number of targets to build, a single worker may give
the best trade-off between compilation speed and resource usage (for example,
see [issue #8586](https://github.com/bazelbuild/bazel/issues/8586).
The `worker_max_instances` flag sets the maximum number of worker instances per
mnemonic and flag set (see below), so in a mixed system you could end up using
quite a lot of memory if you keep the default value. For incremental builds the
benefit of multiple worker instances is even smaller.
This graph shows the from-scratch compilation times for Bazel (target
`//src:bazel`) on a 6-core hyper-threaded Intel Xeon 3.5 GHz Linux workstation
with 64 GB of RAM. For each worker configuration, five clean builds are run and
the average of the last four are taken.
**Figure 1.** Graph of performance improvements of clean builds.
For this configuration, two workers give the fastest compile, though at only 14%
improvement compared to one worker. One worker is a good option if you want to
use less memory.
Incremental compilation typically benefits even more. Clean builds are
relatively rare, but changing a single file between compiles is common, in
particular in test-driven development. The above example also has some non-Java
packaging actions to it that can overshadow the incremental compile time.
Recompiling the Java sources only
(`//src/main/java/com/google/devtools/build/lib/bazel:BazelServer_deploy.jar`)
after changing an internal string constant in
[AbstractContainerizingSandboxedSpawn.java](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/sandbox/AbstractContainerizingSandboxedSpawn.java)
gives a 3x speed-up (average of 20 incremental builds with one warmup build
discarded):
**Figure 2.** Graph of performance improvements of incremental builds.
The speed-up depends on the change being made. A speed-up of a factor 6 is
measured in the above situation when a commonly used constant is changed.
## Modifying persistent workers
You can pass the
[`--worker_extra_flag`](/reference/command-line-reference#flag--worker_extra_flag)
flag to specify start-up flags to workers, keyed by mnemonic. For instance,
passing `--worker_extra_flag=javac=--debug` turns on debugging for Javac only.
Only one worker flag can be set per use of this flag, and only for one mnemonic.
Workers are not just created separately for each mnemonic, but also for
variations in their start-up flags. Each combination of mnemonic and start-up
flags is combined into a `WorkerKey`, and for each `WorkerKey` up to
`worker_max_instances` workers may be created. See the next section for how the
action configuration can also specify set-up flags.
Passing the
[`--worker_sandboxing`](/reference/command-line-reference#flag--worker_sandboxing)
flag makes each worker request use a separate sandbox directory for all its
inputs. Setting up the [sandbox](/docs/sandboxing) takes some extra time,
especially on macOS, but gives a better correctness guarantee. In addition to
the plain boolean form, the flag may be scoped to a worker-key mnemonic as
`--worker_sandboxing==`, allowing sandboxing to be enabled or
disabled per mnemonic (for example
`--worker_sandboxing --worker_sandboxing=Javac=no`). Later values override
earlier ones for the mnemonics they affect, so a later plain
`--worker_sandboxing` re-enables sandboxing for all mnemonics.
The
[`--worker_quit_after_build`](/reference/command-line-reference#flag--worker_quit_after_build)
flag is mainly useful for debugging and profiling. This flag forces all workers
to quit once a build is done. You can also pass
[`--worker_verbose`](/reference/command-line-reference#flag--worker_verbose) to
get more output about what the workers are doing. This flag is reflected in the
`verbosity` field in `WorkRequest`, allowing worker implementations to also be
more verbose.
Workers store their logs in the `/bazel-workers` directory, for
example
`/tmp/_bazel_larsrc/191013354bebe14fdddae77f2679c3ef/bazel-workers/worker-1-Javac.log`.
The file name includes the worker id and the mnemonic. Since there can be more
than one `WorkerKey` per mnemonic, you may see more than `worker_max_instances`
log files for a given mnemonic.
For Android builds, see details at the
[Android Build Performance page](/docs/android-build-performance).
## Implementing persistent workers
See the [creating persistent workers](/remote/creating) page for more
information on how to make a worker.
This example shows a Starlark configuration for a worker that uses JSON:
```python theme={null}
args_file = ctx.actions.declare_file(ctx.label.name + "_args_file")
ctx.actions.write(
output = args_file,
content = "\n".join(["-g", "-source", "1.5"] + ctx.files.srcs),
)
ctx.actions.run(
mnemonic = "SomeCompiler",
executable = "bin/some_compiler_wrapper",
inputs = inputs,
outputs = outputs,
arguments = [ "-max_mem=4G", "@%s" % args_file.path],
execution_requirements = {
"supports-workers" : "1", "requires-worker-protocol" : "json" }
)
```
With this definition, the first use of this action would start with executing
the command line `/bin/some_compiler -max_mem=4G --persistent_worker`. A request
to compile `Foo.java` would then look like:
NOTE: While the protocol buffer specification uses "snake case" (`request_id`),
the JSON protocol uses "camel case" (`requestId`). In this document, we will use
camel case in the JSON examples, but snake case when talking about the field
regardless of protocol.
```json theme={null}
{
"arguments": [ "-g", "-source", "1.5", "Foo.java" ]
"inputs": [
{ "path": "symlinkfarm/input1", "digest": "d49a..." },
{ "path": "symlinkfarm/input2", "digest": "093d..." },
],
}
```
The worker receives this on `stdin` in newline-delimited JSON format (because
`requires-worker-protocol` is set to JSON). The worker then performs the action,
and sends a JSON-formatted `WorkResponse` to Bazel on its stdout. Bazel then
parses this response and manually converts it to a `WorkResponse` proto. To
communicate with the associated worker using binary-encoded protobuf instead of
JSON, `requires-worker-protocol` would be set to `proto`, like this:
```
execution_requirements = {
"supports-workers" : "1" ,
"requires-worker-protocol" : "proto"
}
```
Setting `requires-worker-protocol` also ensures that the selected protocol is
forwarded to any remote execution server via the `persistentWorkerProtocol`
platform property. If you do not include `requires-worker-protocol` in the
execution requirements, Bazel will default the worker communication to use
protobuf.
Bazel derives the `WorkerKey` from the mnemonic and the shared flags, so if this
configuration allowed changing the `max_mem` parameter, a separate worker would
be spawned for each value used. This can lead to excessive memory consumption if
too many variations are used.
Each worker can currently only process one request at a time. The experimental
[multiplex workers](/remote/multiplex) feature allows using multiple
threads, if the underlying tool is multithreaded and the wrapper is set up to
understand this.
In
[this GitHub repo](https://github.com/Ubehebe/bazel-worker-examples),
you can see example worker wrappers written in Java as well as in Python. If you
are working in JavaScript or TypeScript, the
[@bazel/worker package](https://www.npmjs.com/package/@bazel/worker)
and
[nodejs worker example](https://github.com/bazelbuild/rules_nodejs/tree/stable/examples/worker)
might be helpful.
## How do workers affect sandboxing?
Using the `worker` strategy by default does not run the action in a
[sandbox](/docs/sandboxing), similar to the `local` strategy. You can set the
`--worker_sandboxing` flag to run all workers inside sandboxes, making sure each
execution of the tool only sees the input files it's supposed to have, or scope
it per mnemonic with `--worker_sandboxing==`. The tool
may still leak information between requests internally, for instance through a
cache. Using `dynamic` strategy
[requires workers to be sandboxed](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/exec/SpawnStrategyRegistry.java).
To allow correct use of compiler caches with workers, a digest is passed along
with each input file. Thus the compiler or the wrapper can check if the input is
still valid without having to read the file.
Even when using the input digests to guard against unwanted caching, sandboxed
workers offer less strict sandboxing than a pure sandbox, because the tool may
keep other internal state that has been affected by previous requests.
Multiplex workers can only be sandboxed if the worker implementation support it,
and this sandboxing must be separately enabled with the
`--experimental_worker_multiplex_sandboxing` flag. See more details in
[the design doc](https://docs.google.com/document/d/1ncLW0hz6uDhNvci1dpzfEoifwTiNTqiBEm1vi-bIIRM/edit)).
## Further reading
For more information on persistent workers, see:
* [Original persistent workers blog post](https://blog.bazel.build/2015/12/10/java-workers.html)
* [Haskell implementation description](https://www.tweag.io/blog/2019-09-25-bazel-ghc-persistent-worker-internship/)
* [Blog post by Mike Morearty](https://medium.com/@mmorearty/how-to-create-a-persistent-worker-for-bazel-7738bba2cabb)
* [Front End Development with Bazel: Angular/TypeScript and Persistent Workers w/ Asana](https://www.youtube.com/watch?v=0pgERydGyqo)
* [Bazel strategies explained](https://jmmv.dev/2019/12/bazel-strategies.html)
* [Informative worker strategy discussion on the bazel-discuss mailing list](https://groups.google.com/forum/#!msg/bazel-discuss/oAEnuhYOPm8/ol7hf4KWJgAJ)
# Remote Execution Overview
Source: https://bazel.build/remote/rbe
This page covers the benefits, requirements, and options for running Bazel
with remote execution.
By default, Bazel executes builds and tests on your local machine. Remote
execution of a Bazel build allows you to distribute build and test actions
across multiple machines, such as a datacenter.
Remote execution provides the following benefits:
* Faster build and test execution through scaling of nodes available
for parallel actions
* A consistent execution environment for a development team
* Reuse of build outputs across a development team
Bazel uses an open-source
[gRPC protocol](https://github.com/bazelbuild/remote-apis)
to allow for remote execution and remote caching.
For a list of commercially supported remote execution services as well as
self-service tools, see
[Remote Execution Services](/community/remote-execution-services)
## Requirements
Remote execution of Bazel builds imposes a set of mandatory configuration
constraints on the build. For more information, see
[Adapting Bazel Rules for Remote Execution](/remote/rules).
# Adapting Bazel Rules for Remote Execution
Source: https://bazel.build/remote/rules
This page is intended for Bazel users writing custom build and test rules
who want to understand the requirements for Bazel rules in the context of
remote execution.
Remote execution allows Bazel to execute actions on a separate platform, such as
a datacenter. Bazel uses a
[gRPC protocol](https://github.com/bazelbuild/remote-apis/blob/main/build/bazel/remote/execution/v2/remote_execution.proto)
for its remote execution. You can try remote execution with
[bazel-buildfarm](https://github.com/bazelbuild/bazel-buildfarm),
an open-source project that aims to provide a distributed remote execution
platform.
This page uses the following terminology when referring to different
environment types or *platforms*:
* **Host platform** - where Bazel runs.
* **Execution platform** - where Bazel actions run.
* **Target platform** - where the build outputs (and some actions) run.
## Overview
When configuring a Bazel build for remote execution, you must follow the
guidelines described in this page to ensure the build executes remotely
error-free. This is due to the nature of remote execution, namely:
* **Isolated build actions.** Build tools do not retain state and dependencies
cannot leak between them.
* **Diverse execution environments.** Local build configuration is not always
suitable for remote execution environments.
This page describes the issues that can arise when implementing custom Bazel
build and test rules for remote execution and how to avoid them. It covers the
following topics:
* [Invoking build tools through toolchain rules](#toolchain-rules)
* [Managing implicit dependencies](#manage-dependencies)
* [Managing platform-dependent binaries](#manage-binaries)
* [Managing configure-style WORKSPACE rules](#manage-workspace-rules)
## Invoking build tools through toolchain rules
A Bazel toolchain rule is a configuration provider that tells a build rule what
build tools, such as compilers and linkers, to use and how to configure them
using parameters defined by the rule's creator. A toolchain rule allows build
and test rules to invoke build tools in a predictable, preconfigured manner
that's compatible with remote execution. For example, use a toolchain rule
instead of invoking build tools via the `PATH`, `JAVA_HOME`, or other local
variables that may not be set to equivalent values (or at all) in the remote
execution environment.
Toolchain rules currently exist for Bazel build and test rules for
\[Scala]\([https://github.com/bazelbuild/rules\_scala/blob/master/scala/scala\_toolch](https://github.com/bazelbuild/rules_scala/blob/master/scala/scala_toolch) ain.bzl),
[Rust](https://github.com/bazelbuild/rules_rust/blob/main/rust/toolchain.bzl),
and [Go](https://github.com/bazelbuild/rules_go/blob/master/go/toolchains.rst),
and new toolchain rules are under way for other languages and tools such as
[bash](https://docs.google.com/document/d/e/2PACX-1vRCSB_n3vctL6bKiPkIa_RN_ybzoAccSe0ic8mxdFNZGNBJ3QGhcKjsL7YKf-ngVyjRZwCmhi_5KhcX/pub).
If a toolchain rule does not exist for the tool your rule uses, consider
[creating a toolchain rule](/extending/toolchains#creating-a-toolchain-rule).
## Managing implicit dependencies
If a build tool can access dependencies across build actions, those actions will
fail when remotely executed because each remote build action is executed
separately from others. Some build tools retain state across build actions and
access dependencies that have not been explicitly included in the tool
invocation, which will cause remotely executed build actions to fail.
For example, when Bazel instructs a stateful compiler to locally build *foo*,
the compiler retains references to foo's build outputs. When Bazel then
instructs the compiler to build *bar*, which depends on *foo*, without
explicitly stating that dependency in the BUILD file for inclusion in the
compiler invocation, the action executes successfully as long as the same
compiler instance executes for both actions (as is typical for local execution).
However, since in a remote execution scenario each build action executes a
separate compiler instance, compiler state and *bar*'s implicit dependency on
*foo* will be lost and the build will fail.
To help detect and eliminate these dependency problems, Bazel 0.14.1 offers the
local Docker sandbox, which has the same restrictions for dependencies as remote
execution. Use the sandbox to prepare your build for remote execution by
identifying and resolving dependency-related build errors. See [Troubleshooting Bazel Remote Execution with Docker Sandbox](/remote/sandbox)
for more information.
## Managing platform-dependent binaries
Typically, a binary built on the host platform cannot safely execute on an
arbitrary remote execution platform due to potentially mismatched dependencies.
For example, the SingleJar binary supplied with Bazel targets the host platform.
However, for remote execution, SingleJar must be compiled as part of the process
of building your code so that it targets the remote execution platform. (See the
[target selection logic](https://github.com/bazelbuild/bazel/blob/130aeadfd660336572c3da397f1f107f0c89aa8d/tools/jdk/BUILD#L115).)
Do not ship binaries of build tools required by your build with your source code
unless you are sure they will safely run in your execution platform. Instead, do
one of the following:
* Ship or externally reference the source code for the tool so that it can be
built for the remote execution platform.
* Pre-install the tool into the remote execution environment (for example, a
toolchain container) if it's stable enough and use toolchain rules to run it
in your build.
## Managing configure-style WORKSPACE rules
Bazel's `WORKSPACE` rules can be used for probing the host platform for tools
and libraries required by the build, which, for local builds, is also Bazel's
execution platform. If the build explicitly depends on local build tools and
artifacts, it will fail during remote execution if the remote execution platform
is not identical to the host platform.
The following actions performed by `WORKSPACE` rules are not compatible with
remote execution:
* **Building binaries.** Executing compilation actions in `WORKSPACE` rules
results in binaries that are incompatible with the remote execution platform
if different from the host platform.
* **Installing `pip` packages.** `pip` packages installed via `WORKSPACE`
rules require that their dependencies be pre-installed on the host platform.
Such packages, built specifically for the host platform, will be
incompatible with the remote execution platform if different from the host
platform.
* **Symlinking to local tools or artifacts.** Symlinks to tools or libraries
installed on the host platform created via `WORKSPACE` rules will cause the
build to fail on the remote execution platform as Bazel will not be able to
locate them. Instead, create symlinks using standard build actions so that
the symlinked tools and libraries are accessible from Bazel's `runfiles`
tree. Do not use [`repository_ctx.symlink`](/rules/lib/builtins/repository_ctx#symlink)
to symlink target files outside of the external repo directory.
* **Mutating the host platform.** Avoid creating files outside of the Bazel
`runfiles` tree, creating environment variables, and similar actions, as
they may behave unexpectedly on the remote execution platform.
To help find potential non-hermetic behavior you can use [Workspace rules log](/remote/workspace).
If an external dependency executes specific operations dependent on the host
platform, you should split those operations between `WORKSPACE` and build
rules as follows:
* **Platform inspection and dependency enumeration.** These operations are
safe to execute locally via `WORKSPACE` rules, which can check which
libraries are installed, download packages that must be built, and prepare
required artifacts for compilation. For remote execution, these rules must
also support using pre-checked artifacts to provide the information that
would normally be obtained during host platform inspection. Pre-checked
artifacts allow Bazel to describe dependencies as if they were local. Use
conditional statements or the `--override_repository` flag for this.
* **Generating or compiling target-specific artifacts and platform mutation**.
These operations must be executed via regular build rules. Actions that
produce target-specific artifacts for external dependencies must execute
during the build.
To more easily generate pre-checked artifacts for remote execution, you can use
`WORKSPACE` rules to emit generated files. You can run those rules on each new
execution environment, such as inside each toolchain container, and check the
outputs of your remote execution build in to your source repo to reference.
For example, for Tensorflow's rules for [`cuda`](https://github.com/tensorflow/tensorflow/blob/master/third_party/gpus/cuda_configure.bzl)
and [`python`](https://github.com/tensorflow/tensorflow/blob/master/third_party/py/python_configure.bzl),
the `WORKSPACE` rules produce the following [`BUILD files`](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/tools/third_party/toolchains/cpus/py).
For local execution, files produced by checking the host environment are used.
For remote execution, a [conditional statement](https://github.com/tensorflow/tensorflow/blob/master/third_party/py/python_configure.bzl#L304)
on an environment variable allows the rule to use files that are checked into
the repo.
The `BUILD` files declare [`genrules`](https://github.com/tensorflow/tensorflow/blob/master/third_party/py/python_configure.bzl#L84)
that can run both locally and remotely, and perform the necessary processing
that was previously done via `repository_ctx.symlink` as shown [here](https://github.com/tensorflow/tensorflow/blob/d1ba01f81d8fa1d0171ba9ce871599063d5c7eb9/third_party/gpus/cuda_configure.bzl#L730).
# Troubleshooting Bazel Remote Execution with Docker Sandbox
Source: https://bazel.build/remote/sandbox
Bazel builds that succeed locally may fail when executed remotely due to
restrictions and requirements that do not affect local builds. The most common
causes of such failures are described in [Adapting Bazel Rules for Remote Execution](/remote/rules).
This page describes how to identify and resolve the most common issues that
arise with remote execution using the Docker sandbox feature, which imposes
restrictions upon the build equal to those of remote execution. This allows you
to troubleshoot your build without the need for a remote execution service.
The Docker sandbox feature mimics the restrictions of remote execution as
follows:
* **Build actions execute in toolchain containers.** You can use the same
toolchain containers to run your build locally and remotely via a service
supporting containerized remote execution.
* **No extraneous data crosses the container boundary.** Only explicitly
declared inputs and outputs enter and leave the container, and only after
the associated build action successfully completes.
* **Each action executes in a fresh container.** A new, unique container is
created for each spawned build action.
Note: Builds take noticeably more time to complete when the Docker sandbox
feature is enabled. This is normal.
You can troubleshoot these issues using one of the following methods:
* **[Troubleshooting natively.](#troubleshooting-natively)** With this method,
Bazel and its build actions run natively on your local machine. The Docker
sandbox feature imposes restrictions upon the build equal to those of remote
execution. However, this method will not detect local tools, states, and
data leaking into your build, which will cause problems with remote execution.
* **[Troubleshooting in a Docker container.](#troubleshooting-docker-container)**
With this method, Bazel and its build actions run inside a Docker container,
which allows you to detect tools, states, and data leaking from the local
machine into the build in addition to imposing restrictions
equal to those of remote execution. This method provides insight into your
build even if portions of the build are failing. This method is experimental
and not officially supported.
## Prerequisites
Before you begin troubleshooting, do the following if you have not already done so:
* Install Docker and configure the permissions required to run it.
* Install Bazel 0.14.1 or later. Earlier versions do not support the Docker
sandbox feature.
* Add the [bazel-toolchains](https://releases.bazel.build/bazel-toolchains.html)
repo, pinned to the latest release version, to your build's `WORKSPACE` file
as described [here](https://releases.bazel.build/bazel-toolchains.html).
* Add flags to your `.bazelrc` file to enable the feature. Create the file in
the root directory of your Bazel project if it does not exist. Flags below
are a reference sample. Please see the latest
[`.bazelrc`](https://github.com/bazelbuild/bazel-toolchains/tree/master/bazelrc)
file in the bazel-toolchains repo and copy the values of the flags defined
there for config `docker-sandbox`.
```
# Docker Sandbox Mode
build:docker-sandbox --host_javabase=<...>
build:docker-sandbox --javabase=<...>
build:docker-sandbox --crosstool_top=<...>
build:docker-sandbox --experimental_docker_image=<...>
build:docker-sandbox --spawn_strategy=docker --strategy=Javac=docker --genrule_strategy=docker
build:docker-sandbox --experimental_docker_verbose
build:docker-sandbox --experimental_enable_docker_sandbox
```
Note: The flags referenced in the `.bazelrc` file shown above are configured
to run within the [`rbe-ubuntu16-04`](https://console.cloud.google.com/launcher/details/google/rbe-ubuntu16-04)
container.
If your rules require additional tools, do the following:
1. Create a custom Docker container by installing tools using a [Dockerfile](https://docs.docker.com/engine/reference/builder/)
and [building](https://docs.docker.com/engine/reference/commandline/build/)
the image locally.
2. Replace the value of the `--experimental_docker_image` flag above with the
name of your custom container image.
## Troubleshooting natively
This method executes Bazel and all of its build actions directly on the local
machine and is a reliable way to confirm whether your build will succeed when
executed remotely.
However, with this method, locally installed tools, binaries, and data may leak
into your build, especially if it uses [configure-style WORKSPACE rules](/remote/rules#manage-workspace-rules).
Such leaks will cause problems with remote execution; to detect them, [troubleshoot in a Docker container](#troubleshooting-docker-container)
in addition to troubleshooting natively.
### Step 1: Run the build
1. Add the `--config=docker-sandbox` flag to the Bazel command that executes
your build. For example:
```posix-terminal theme={null}
bazel --bazelrc=.bazelrc build --config=docker-sandbox target
```
2. Run the build and wait for it to complete. The build will run up to four
times slower than normal due to the Docker sandbox feature.
You may encounter the following error:
```none theme={null}
ERROR: 'docker' is an invalid value for docker spawn strategy.
```
If you do, run the build again with the `--experimental_docker_verbose` flag.
This flag enables verbose error messages. This error is typically caused by a
faulty Docker installation or lack of permissions to execute it under the
current user account. See the [Docker documentation](https://docs.docker.com/install/linux/linux-postinstall/)
for more information. If problems persist, skip ahead to [Troubleshooting in a Docker container](#troubleshooting-docker-container).
### Step 2: Resolve detected issues
The following are the most commonly encountered issues and their workarounds.
* **A file, tool, binary, or resource referenced by the Bazel runfiles tree is
missing.**. Confirm that all dependencies of the affected targets have been
[explicitly declared](/concepts/dependencies). See
[Managing implicit dependencies](/remote/rules#manage-dependencies)
for more information.
* **A file, tool, binary, or resource referenced by an absolute path or the `PATH`
variable is missing.** Confirm that all required tools are installed within
the toolchain container and use [toolchain rules](/extending/toolchains) to properly
declare dependencies pointing to the missing resource. See
[Invoking build tools through toolchain rules](/remote/rules#invoking-build-tools-through-toolchain-rules)
for more information.
* **A binary execution fails.** One of the build rules is referencing a binary
incompatible with the execution environment (the Docker container). See
[Managing platform-dependent binaries](/remote/rules#manage-binaries)
for more information. If you cannot resolve the issue, contact [bazel-discuss@google.com](mailto:bazel-discuss@google.com)
for help.
* **A file from `@local-jdk` is missing or causing errors.** The Java binaries
on your local machine are leaking into the build while being incompatible with
it. Use [`java_toolchain`](/reference/be/java#java_toolchain)
in your rules and targets instead of `@local_jdk`. Contact [bazel-discuss@google.com](mailto:bazel-discuss@google.com) if you need further help.
* **Other errors.** Contact [bazel-discuss@google.com](mailto:bazel-discuss@google.com) for help.
## Troubleshooting in a Docker container
With this method, Bazel runs inside a host Docker container, and Bazel's build
actions execute inside individual toolchain containers spawned by the Docker
sandbox feature. The sandbox spawns a brand new toolchain container for each
build action and only one action executes in each toolchain container.
This method provides more granular control of tools installed in the host
environment. By separating the execution of the build from the execution of its
build actions and keeping the installed tooling to a minimum, you can verify
whether your build has any dependencies on the local execution environment.
### Step 1: Build the container
Note: The commands below are tailored specifically for a `debian:stretch` base.
For other bases, modify them as necessary.
1. Create a `Dockerfile` that creates the Docker container and installs Bazel
with a minimal set of build tools:
```
FROM debian:stretch
RUN apt-get update && apt-get install -y apt-transport-https curl software-properties-common git gcc gnupg2 g++ openjdk-8-jdk-headless python-dev zip wget vim
RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add -
RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable"
RUN apt-get update && apt-get install -y docker-ce
RUN wget https://releases.bazel.build//release/bazel--installer-linux-x86_64.sh -O ./bazel-installer.sh && chmod 755 ./bazel-installer.sh
RUN ./bazel-installer.sh
```
2. Build the container as `bazel_container`:
```posix-terminal theme={null}
docker build -t bazel_container - < Dockerfile
```
### Step 2: Start the container
Start the Docker container using the command shown below. In the command,
substitute the path to the source code on your host that you want to build.
```posix-terminal theme={null}
docker run -it \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /tmp:/tmp \
-v your source code directory:/src \
-w /src \
bazel_container \
/bin/bash
```
This command runs the container as root, mapping the docker socket, and mounting
the `/tmp` directory. This allows Bazel to spawn other Docker containers and to
use directories under `/tmp` to share files with those containers. Your source
code is available at `/src` inside the container.
The command intentionally starts from a `debian:stretch` base container that
includes binaries incompatible with the `rbe-ubuntu16-04` container used as a
toolchain container. If binaries from the local environment are leaking into the
toolchain container, they will cause build errors.
### Step 3: Test the container
Run the following commands from inside the Docker container to test it:
```posix-terminal theme={null}
docker ps
bazel version
```
### Step 4: Run the build
Run the build as shown below. The output user is root so that it corresponds to
a directory that is accessible with the same absolute path from inside the host
container in which Bazel runs, from the toolchain containers spawned by the Docker
sandbox feature in which Bazel's build actions are running, and from the local
machine on which the host and action containers run.
```posix-terminal theme={null}
bazel --output_user_root=/tmp/bazel_docker_root --bazelrc=.bazelrc \ build --config=docker-sandbox target
```
### Step 5: Resolve detected issues
You can resolve build failures as follows:
* If the build fails with an "out of disk space" error, you can increase this
limit by starting the host container with the flag `--memory=XX` where `XX`
is the allocated disk space in gigabytes. This is experimental and may
result in unpredictable behavior.
* If the build fails during the analysis or loading phases, one or more of
your build rules declared in the WORKSPACE file are not compatible with
remote execution. See [Adapting Bazel Rules for Remote Execution](/remote/rules)
for possible causes and workarounds.
* If the build fails for any other reason, see the troubleshooting steps in [Step 2: Resolve detected issues](#start-container).
# Finding Non-Hermetic Behavior in WORKSPACE Rules
Source: https://bazel.build/remote/workspace
In the following, a host machine is the machine where Bazel runs.
When using remote execution, the actual build and/or test steps are not
happening on the host machine, but are instead sent off to the remote execution
system. However, the steps involved in resolving workspace rules are happening
on the host machine. If your workspace rules access information about the
host machine for use during execution, your build is likely to break due to
incompatibilities between the environments.
As part of [adapting Bazel rules for remote execution](/remote/rules), you need to find such workspace rules
and fix them. This page describes how to find potentially problematic workspace
rules using the workspace log.
## Finding non-hermetic rules
[Repository rules](/external/repo) allow the developer to add dependencies to
external workspaces, but they are rich enough to allow arbitrary processing to
happen in the process. All related commands are happening locally and can be a
potential source of non-hermeticity. Usually non-hermetic behavior is
introduced through
[`repository_ctx`](/rules/lib/builtins/repository_ctx) which allows interacting
with the host machine.
Starting with Bazel 0.18, you can get a log of some potentially non-hermetic
actions by adding the flag `--experimental_workspace_rules_log_file=[PATH]` to
your Bazel command. Here `[PATH]` is a filename under which the log will be
created.
Things to note:
* the log captures the events as they are executed. If some steps are
cached, they will not show up in the log, so to get a full result, don't
forget to run `bazel clean --expunge` beforehand.
* Sometimes functions might be re-executed, in which case the related
events will show up in the log multiple times.
* Workspace rules currently only log Starlark events.
Note: These particular rules do not cause hermiticity concerns as long
as a hash is specified.
To find what was executed during workspace initialization:
1. Run `bazel clean --expunge`. This command will clean your local cache and
any cached repositories, ensuring that all initialization will be re-run.
2. Add `--experimental_workspace_rules_log_file=/tmp/workspacelog` to your
Bazel command and run the build.
This produces a binary proto file listing messages of type
[WorkspaceEvent](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/bazel/debug/workspace_log.proto?q=WorkspaceEvent)
3. Download the Bazel source code and navigate to the Bazel folder by using
the command below. You need the source code to be able to parse the
workspace log with the
[workspacelog parser](https://source.bazel.build/bazel/+/master:src/tools/workspacelog/).
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/bazel.git
cd bazel
```
4. In the Bazel source code repo, convert the whole workspace log to text.
```posix-terminal theme={null}
bazel build src/tools/workspacelog:parser
bazel-bin/src/tools/workspacelog/parser --log_path=/tmp/workspacelog > /tmp/workspacelog.txt
```
5. The output may be quite verbose and include output from built in Bazel
rules.
To exclude specific rules from the output, use `--exclude_rule` option.
For example:
```posix-terminal theme={null}
bazel build src/tools/workspacelog:parser
bazel-bin/src/tools/workspacelog/parser --log_path=/tmp/workspacelog \
--exclude_rule "//external:local_config_cc" \
--exclude_rule "//external:dep" > /tmp/workspacelog.txt
```
6. Open `/tmp/workspacelog.txt` and check for unsafe operations.
The log consists of
[WorkspaceEvent](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/bazel/debug/workspace_log.proto?q=WorkspaceEvent)
messages outlining certain potentially non-hermetic actions performed on a
[`repository_ctx`](/rules/lib/builtins/repository_ctx).
The actions that have been highlighted as potentially non-hermetic are as follows:
* `execute`: executes an arbitrary command on the host environment. Check if
these may introduce any dependencies on the host environment.
* `download`, `download_and_extract`: to ensure hermetic builds, make sure
that sha256 is specified
* `file`, `template`: this is not non-hermetic in itself, but may be a mechanism
for introducing dependencies on the host environment into the repository.
Ensure that you understand where the input comes from, and that it does not
depend on the host environment.
* `os`: this is not non-hermetic in itself, but an easy way to get dependencies
on the host environment. A hermetic build would generally not call this.
In evaluating whether your usage is hermetic, keep in mind that this is
running on the host and not on the workers. Getting environment specifics
from the host is generally not a good idea for remote builds.
* `symlink`: this is normally safe, but look for red flags. Any symlinks to
outside the repository or to an absolute path would cause problems on the
remote worker. If the symlink is created based on host machine properties
it would probably be problematic as well.
* `which`: checking for programs installed on the host is usually problematic
since the workers may have different configurations.
# Write bazelrc configuration files
Source: https://bazel.build/run/bazelrc
Bazel accepts many options. Some options are varied frequently (for example,
`--subcommands`) while others stay the same across several builds (such as
`--package_path`). To avoid specifying these unchanged options for every build
(and other commands), you can specify options in a configuration file, called
`.bazelrc`.
### Where are the `.bazelrc` files?
Bazel looks for optional configuration files in the following locations,
in the order shown below. The options are interpreted in this order, so
options in later files can override a value from an earlier file if a
conflict arises. All options that control which of these files are loaded are
startup options, which means they must occur after `bazel` and
before the command (`build`, `test`, etc).
1. **The system RC file**, unless `--nosystem_rc` is present.
Path:
* On Linux/macOS/Unixes: `/etc/bazel.bazelrc`
* On Windows: `%ProgramData%\bazel.bazelrc`
It is not an error if this file does not exist.
If another system-specified location is required, you must build a custom
Bazel binary, overriding the `BAZEL_SYSTEM_BAZELRC_PATH` value in
[`//src/main/cpp:option_processor`](https://github.com/bazelbuild/bazel/blob/0.28.0/src/main/cpp/BUILD#L141).
The system-specified location may contain environment variable references,
such as `${VAR_NAME}` on Unix or `%VAR_NAME%` on Windows.
2. **The workspace RC file**, unless `--noworkspace_rc` is present.
Path: `.bazelrc` in your workspace directory (next to the main
`MODULE.bazel` file).
It is not an error if this file does not exist.
3. **The home RC file**, unless `--nohome_rc` is present.
Path:
* On Linux/macOS/Unixes: `$HOME/.bazelrc`
* On Windows: `%USERPROFILE%\.bazelrc` if exists, or `%HOME%/.bazelrc`
It is not an error if this file does not exist.
4. **The environment variable RC file**, if its path is set with the `BAZELRC`
environment variable.
The environment variable can include multiple comma-separated paths.
5. **The user-specified RC file**, if specified with
--bazelrc=file
This flag is optional but can also be specified multiple times.
`/dev/null` indicates that all further `--bazelrc`s will be ignored, which
is useful to disable the search for a user rc file, such as in release
builds.
For example:
```
--bazelrc=x.rc --bazelrc=y.rc --bazelrc=/dev/null --bazelrc=z.rc
```
* `x.rc` and `y.rc` are read.
* `z.rc` is ignored due to the prior `/dev/null`.
In addition to this optional configuration file, Bazel looks for a global rc
file. For more details, see the [global bazelrc section](#global-bazelrc).
### `.bazelrc` syntax and semantics
Like all UNIX "rc" files, the `.bazelrc` file is a text file with a line-based
grammar. Empty lines and lines starting with `#` (comments) are ignored. Each
line contains a sequence of words, which are tokenized according to the same
rules as the Bourne shell.
#### Imports
Lines that start with `import`, `try-import` or `try-import-if-bazel-version`
are special: use these to load other "rc" files. To specify a path that is
relative to the workspace root, write `import %workspace%/path/to/bazelrc`.
The difference between the various import statements is as follows:
* `import` - Bazel will fail if the `import`'ed file is missing (or can't be
read)
* `try-import` - An attempt to import the file will be made, but unlike
`import`, Bazel will NOT fail if the file is missing (or can't be read).
* `try-import-if-bazel-version` - Similar to `try-import`, but an additional
condition on the current Bazel version is checked before attempting to do
the import. See below for the syntax.
Conditional Bazel version imports can be useful if a project needs to work under
several Bazel versions or during the transition from one Bazel version to
another. Different flags may be needed for different Bazel versions since flags
may be deprecated, removed or introduced in each release. To check which version
of Bazel you have, run `bazel --version`. The following conditional checks are
supported and require valid semantic versions:
```none theme={null}
# Strictly greater than: used for post-release targeting
try-import-if-bazel-version >7.0.0 %workspace%/configs/post_v7.rc
# Greater than or equal to: commonly used for feature introduction
try-import-if-bazel-version >=6.0.0 %workspace%/configs/features.rc
# Strictly less than: used for deprecated flags removed in newer versions
try-import-if-bazel-version <7.0.0 %workspace%/configs/legacy.rc
# Less than or equal to: caps configuration to a specific version
try-import-if-bazel-version <=5.4.0 %workspace%/configs/v5_fixes.rc
# Exact match: hotfix for a specific broken release
try-import-if-bazel-version ==6.3.2 %workspace%/configs/hotfix_6.3.2.rc
# Not equal to: excludes broken version from standard config
try-import-if-bazel-version !=7.0.1 %workspace%/configs/standard.rc
```
An additional tilde operator provides ranges for patch, minor, and major version
changes:
```none theme={null}
# Equivalent to >=1.2.3 <1.3.0
try-import-if-bazel-version ~1.2.3 %workspace%/configs/1.2.3_flags.rc
# Equivalent to >=1.2.0 <1.3.0 (Same as 1.2.x)
try-import-if-bazel-version ~1.2 %workspace%/configs/1.2_flags.rc
# Equivalent to >=1.0.0 <2.0.0 (Same as 1.x)
try-import-if-bazel-version ~1 %workspace%/configs/v1_flags.rc
```
Import precedence:
* Options in the imported file take precedence over options specified before
the import statement.
* Options specified after the import statement take precedence over the
options in the imported file.
* Options in files imported later take precedence over files imported earlier.
#### Option defaults
Most lines of a bazelrc define default option values. The first word on each
line specifies when these defaults are applied:
* `startup`: startup options, which go before the command, and are described
in `bazel help startup_options`.
* `common`: options that should be applied to all Bazel commands that support
them. If a command does not support an option specified in this way, the
option is ignored so long as it is valid for *some* other Bazel command.
Note that this only applies to option names: If the current command accepts
an option with the specified name, but doesn't support the specified value,
it will fail.
* `always`: options that apply to all Bazel commands. If a command does not
support an option specified in this way, it will fail.
* *`command`*: Bazel command, such as `build` or `query` to which the options
apply. These options also apply to all commands that inherit from the
specified command. (For example, `test` inherits from `build`.)
Each of these lines may be used more than once and the arguments that follow the
first word are combined as if they had appeared on a single line. (Users of CVS,
another tool with a "Swiss army knife" command-line interface, will find the
syntax similar to that of `.cvsrc`.) For example, the lines:
```posix-terminal theme={null}
build --test_tmpdir=/tmp/foo --verbose_failures
build --test_tmpdir=/tmp/bar
```
are combined as:
```posix-terminal theme={null}
build --test_tmpdir=/tmp/foo --verbose_failures --test_tmpdir=/tmp/bar
```
so the effective flags are `--verbose_failures` and `--test_tmpdir=/tmp/bar`.
Option precedence:
* Options on the command line always take precedence over those in rc files.
For example, if a rc file says `build -c opt` but the command line flag is
`-c dbg`, the command line flag takes precedence.
* Within the rc file, precedence is governed by specificity: lines for a more
specific command take precedence over lines for a less specific command.
Specificity is defined by inheritance. Some commands inherit options from
other commands, making the inheriting command more specific than the base
command. For example `test` inherits from the `build` command, so all `bazel
build` flags are valid for `bazel test`, and all `build` lines apply also to
`bazel test` unless there's a `test` line for the same option. If the rc
file says:
```posix-terminal theme={null}
test -c dbg --test_env=PATH
build -c opt --verbose_failures
```
then `bazel build //foo` will use `-c opt --verbose_failures`, and `bazel
test //foo` will use `--verbose_failures -c dbg --test_env=PATH`.
The inheritance (specificity) graph is:
* Every command inherits from `common`
* The following commands inherit from (and are more specific than)
`build`: `test`, `run`, `clean`, `mobile-install`, `info`,
`print_action`, `config`, `cquery`, and `aquery`
* `coverage`, `fetch`, and `vendor` inherit from `test`
* Two lines specifying options for the same command at equal specificity are
parsed in the order in which they appear within the file.
* Because this precedence rule does not match the file order, it helps
readability if you follow the precedence order within rc files: start with
`common` options at the top, and end with the most-specific commands at the
bottom of the file. This way, the order in which the options are read is the
same as the order in which they are applied, which is more intuitive.
The arguments specified on a line of an rc file may include arguments that are
not options, such as the names of build targets, and so on. These, like the
options specified in the same files, have lower precedence than their siblings
on the command line, and are always prepended to the explicit list of non-
option arguments.
#### `--config`
In addition to setting option defaults, the rc file can be used to group options
and provide a shorthand for common groupings. This is done by adding a `:name`
suffix to the command. These options are ignored by default, but will be
included when the option --config=name is present,
either on the command line or in a `.bazelrc` file, recursively, even inside of
another config definition. The options specified by `command:name` will only be
expanded for applicable commands, in the precedence order described above.
Note: Configs can be defined in any `.bazelrc` file, and that all lines of
the form `command:name` (for applicable commands) will be expanded, across the
different rc files. In order to avoid name conflicts, we suggest that configs
defined in personal rc files start with an underscore (`_`) to avoid
unintentional name sharing.
`--config=foo` expands to the options defined in
[the rc files](#bazelrc-file-locations) "in-place" so that the options
specified for the config have the same precedence that the `--config=foo` option
had.
This syntax does not extend to the use of `startup` to set
[startup options](#option-defaults). Setting
`startup:config-name --some_startup_option` in the .bazelrc will be ignored.
#### `--enable_platform_specific_config`
Platform specific configs in the `.bazelrc` can be automatically enabled using
`--enable_platform_specific_config`. For example, if the host OS is Linux and
the `build` command is run, the `build:linux` configuration will be
automatically enabled. Supported OS identifiers are `linux`, `macos`, `windows`,
`freebsd`, and `openbsd`. Enabling this flag is equivalent to using
`--config=linux` on Linux, `--config=windows` on Windows, and so on.
See [--enable\_platform\_specific\_config](/reference/command-line-reference#flag--enable_platform_specific_config).
Platform specific configurations also apply to `startup` options. For
example `startup:linux --some_startup_option` will be applied when the
host OS is Linux. Supported OS identifiers are `linux`, `macos`,
`windows`, `freebsd`, and `openbsd`. This behavior is always enabled.
#### Example
Here's an example `~/.bazelrc` file:
```
# Bob's Bazel option defaults
startup --host_jvm_args=-XX:-UseParallelGC
import /home/bobs_project/bazelrc
build --show_timestamps --keep_going --jobs 600
build --color=yes
query --keep_going
# Definition of --config=memcheck
build:memcheck --strip=never --test_timeout=3600
```
### Other files governing Bazel's behavior
#### `.bazelignore`
You can specify directories within the workspace
that you want Bazel to ignore, such as related projects
that use other build systems. Place a file called
`.bazelignore` at the root of the workspace
and add the directories you want Bazel to ignore, one per
line. Entries are relative to the workspace root.
The `.bazelignore` file does not permit glob semantics.
Bazel 8 introduces the `REPO.bazel` file which allows another directive, `ignore_directories()`.
It takes a list of directories to ignore just like .bazelignore does, but with glob semantics.
See [#24203](https://github.com/bazelbuild/bazel/pull/24203).
### The global bazelrc file
Bazel reads optional bazelrc files in this order:
1. System rc-file located at `/etc/bazel.bazelrc`.
2. Workspace rc-file located at `$workspace/.bazelrc`.
3. Home rc-file located at `$HOME/.bazelrc`
Each bazelrc file listed here has a corresponding flag which can be used to
disable them (e.g. `--nosystem_rc`, `--noworkspace_rc`, `--nohome_rc`). You can
also make Bazel ignore all bazelrcs by passing the `--ignore_all_rc_files`
startup option.
# Build programs with Bazel
Source: https://bazel.build/run/build
This page covers how to build a program with Bazel, build command syntax, and
target pattern syntax.
## Quickstart
To run Bazel, go to your base [workspace](/concepts/build-ref#workspace) directory
or any of its subdirectories and type `bazel`. See [build](#bazel-build) if you
need to make a new workspace.
```posix-terminal theme={null}
bazel help
[Bazel release bazel version]
Usage: bazel commandoptions ...
```
### Available commands
* [`aquery`](/docs/user-manual#aquery): Executes a query on the [post-analysis](#analysis) action graph.
* [`build`](#bazel-build): Builds the specified targets.
* [`canonicalize-flags`](/docs/user-manual#canonicalize-flags): Canonicalize Bazel flags.
* [`clean`](/docs/user-manual#clean): Removes output files and optionally stops the server.
* [`cquery`](/query/cquery): Executes a [post-analysis](#analysis) dependency graph query.
* [`dump`](/docs/user-manual#dump): Dumps the internal state of the Bazel server process.
* [`help`](/docs/user-manual#help): Prints help for commands, or the index.
* [`info`](/docs/user-manual#info): Displays runtime info about the bazel server.
* [`fetch`](#fetching-external-dependencies): Fetches all external dependencies of a target.
* [`mobile-install`](/docs/user-manual#mobile-install): Installs apps on mobile devices.
* [`query`](/query/guide): Executes a dependency graph query.
* [`run`](/docs/user-manual#running-executables): Runs the specified target.
* [`shutdown`](/docs/user-manual#shutdown): Stops the Bazel server.
* [`test`](/docs/user-manual#running-tests): Builds and runs the specified test targets.
* [`version`](/docs/user-manual#version): Prints version information for Bazel.
### Getting help
* `bazel help command`: Prints help and options for
`command`.
* `bazel help `[`startup_options`](/docs/user-manual#startup-options): Options for the JVM hosting Bazel.
* `bazel help `[`target-syntax`](#specifying-build-targets): Explains the syntax for specifying targets.
* `bazel help info-keys`: Displays a list of keys used by the info command.
The `bazel` tool performs many functions, called commands. The most commonly
used ones are `bazel build` and `bazel test`. You can browse the online help
messages using `bazel help`.
### Building one target
Before you can start a build, you need a *workspace*. A workspace is a
directory tree that contains all the source files needed to build your
application. Bazel allows you to perform a build from a completely read-only
volume.
To build a program with Bazel, type `bazel build` followed by the
[target](#specifying-build-targets) you want to build.
```posix-terminal theme={null}
bazel build //foo
```
After issuing the command to build `//foo`, you'll see output similar to this:
```
INFO: Analyzed target //foo:foo (14 packages loaded, 48 targets configured).
INFO: Found 1 target...
Target //foo:foo up-to-date:
bazel-bin/foo/foo
INFO: Elapsed time: 9.905s, Critical Path: 3.25s
INFO: Build completed successfully, 6 total actions
```
First, Bazel **loads** all packages in your target's dependency graph. This
includes *declared dependencies*, files listed directly in the target's `BUILD`
file, and *transitive dependencies*, files listed in the `BUILD` files of your
target's dependencies. After identifying all dependencies, Bazel **analyzes**
them for correctness and creates the *build actions*. Last, Bazel **executes**
the compilers and other tools of the build.
During the build's execution phase, Bazel prints progress messages. The progress
messages include the current build step (such as, compiler or linker) as it
starts, and the number completed over the total number of build actions. As the
build starts, the number of total actions often increases as Bazel discovers
the entire action graph, but the number stabilizes within a few seconds.
At the end of the build, Bazel prints which targets were requested, whether or
not they were successfully built, and if so, where the output files can be
found. Scripts that run builds can reliably parse this output; see
[`--show_result`](/docs/user-manual#show-result) for more details.
If you type the same command again, the build finishes much faster.
```posix-terminal theme={null}
bazel build //foo
INFO: Analyzed target //foo:foo (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //foo:foo up-to-date:
bazel-bin/foo/foo
INFO: Elapsed time: 0.144s, Critical Path: 0.00s
INFO: Build completed successfully, 1 total action
```
This is a *null build*. Because nothing changed, there are no packages to reload
and no build steps to execute. If something changed in 'foo' or its
dependencies, Bazel would re-execute some build actions, or complete an
*incremental build*.
### Building multiple targets
Bazel allows a number of ways to specify the targets to be built. Collectively,
these are known as *target patterns*. This syntax is used in commands like
`build`, `test`, or `query`.
Whereas [labels](/concepts/labels) are used to specify individual
targets, such as for declaring dependencies in `BUILD` files, Bazel's target
patterns specify multiple targets. Target patterns are a generalization of the
label syntax for *sets* of targets, using wildcards. In the simplest case, any
valid label is also a valid target pattern, identifying a set of exactly one
target.
All target patterns starting with `//` are resolved relative to the current
workspace.
//foo/bar:wiz
Just the single target //foo/bar:wiz.
//foo/bar
Equivalent to //foo/bar:bar.
//foo/bar:all
All rule targets in the package foo/bar.
//foo/...
All rule targets in all packages beneath the directory foo.
//foo/...:all
All rule targets in all packages beneath the directory foo.
//foo/...:\*
All targets (rules and files) in all packages beneath the directory foo.
//foo/...:all-targets
All targets (rules and files) in all packages beneath the directory foo.
//...
All rule targets in packages in the main repository. Does not include targets
from external repositories.
//:all
All rule targets in the top-level package, if there is a `BUILD` file at the
root of the workspace.
Target patterns that do not begin with `//` are resolved relative to the
current *working directory*. These examples assume a working directory of `foo`:
:foo
Equivalent to //foo:foo.
bar:wiz
Equivalent to //foo/bar:wiz.
bar/wiz
Equivalent to:
//foo/bar/wiz:wiz if foo/bar/wiz is a package
//foo/bar:wiz if foo/bar is a package
//foo:bar/wiz otherwise
bar:all
Equivalent to //foo/bar:all.
:all
Equivalent to //foo:all.
...:all
Equivalent to //foo/...:all.
...
Equivalent to //foo/...:all.
bar/...:all
Equivalent to //foo/bar/...:all.
By default, directory symlinks are followed for recursive target patterns,
except those that point to under the output base, such as the convenience
symlinks that are created in the root directory of the workspace.
In addition, Bazel does not follow symlinks when evaluating recursive target
patterns in any directory that contains a file named as follows:
`DONT_FOLLOW_SYMLINKS_WHEN_TRAVERSING_THIS_DIRECTORY_VIA_A_RECURSIVE_TARGET_PATTERN`
`foo/...` is a wildcard over *packages*, indicating all packages recursively
beneath directory `foo` (for all roots of the package path). `:all` is a
wildcard over *targets*, matching all rules within a package. These two may be
combined, as in `foo/...:all`, and when both wildcards are used, this may be
abbreviated to `foo/...`.
In addition, `:*` (or `:all-targets`) is a wildcard that matches *every target*
in the matched packages, including files that aren't normally built by any rule,
such as `_deploy.jar` files associated with `java_binary` rules.
This implies that `:*` denotes a *superset* of `:all`; while potentially
confusing, this syntax does allow the familiar `:all` wildcard to be used for
typical builds, where building targets like the `_deploy.jar` is not desired.
In addition, Bazel allows a slash to be used instead of the colon required by
the label syntax; this is often convenient when using Bash filename expansion.
For example, `foo/bar/wiz` is equivalent to `//foo/bar:wiz` (if there is a
package `foo/bar`) or to `//foo:bar/wiz` (if there is a package `foo`).
Many Bazel commands accept a list of target patterns as arguments, and they all
honor the prefix negation operator `-`. This can be used to subtract a set of
targets from the set specified by the preceding arguments. Note that this means
order matters. For example,
```posix-terminal theme={null}
bazel build foo/... bar/...
```
means "build all targets beneath `foo` *and* all targets beneath `bar`", whereas
```posix-terminal theme={null}
bazel build -- foo/... -foo/bar/...
```
means "build all targets beneath `foo` *except* those beneath `foo/bar`". (The
`--` argument is required to prevent the subsequent arguments starting with `-`
from being interpreted as additional options.)
It's important to point out though that subtracting targets this way will not
guarantee that they are not built, since they may be dependencies of targets
that weren't subtracted. For example, if there were a target `//foo:all-apis`
that among others depended on `//foo/bar:api`, then the latter would be built as
part of building the former.
Targets with `tags = ["manual"]` are not included in wildcard target patterns
(`...`, `:*`, `:all`, etc.) when specified in commands like
`bazel build` and `bazel test` (but they are included in
negative wildcard target patterns, that is they will be subtracted). You should
specify such test targets with explicit target patterns on the command line if
you want Bazel to build/test them. In contrast, `bazel query` doesn't perform
any such filtering automatically (that would defeat the purpose of
`bazel query`).
### Fetching external dependencies
By default, Bazel will download and symlink external dependencies during the
build. However, this can be undesirable, either because you'd like to know
when new external dependencies are added or because you'd like to
"prefetch" dependencies (say, before a flight where you'll be offline). If you
would like to prevent new dependencies from being added during builds, you
can specify the `--fetch=false` flag. Note that this flag only
applies to repository rules that do not point to a directory in the local
file system. Changes, for example, to `local_repository`,
`new_local_repository` and Android SDK and NDK repository rules
will always take effect regardless of the value `--fetch` .
If you disallow fetching during builds and Bazel finds new external
dependencies, your build will fail.
You can manually fetch dependencies by running `bazel fetch`. If
you disallow during-build fetching, you'll need to run `bazel fetch`:
* Before you build for the first time.
* After you add a new external dependency.
Once it has been run, you should not need to run it again until the MODULE.bazel
file changes.
`fetch` takes a list of targets to fetch dependencies for. For
example, this would fetch dependencies needed to build `//foo:bar`
and `//bar:baz`:
```posix-terminal theme={null}
bazel fetch //foo:bar //bar:baz
```
To fetch all external dependencies for a workspace, run:
```posix-terminal theme={null}
bazel fetch //...
```
With Bazel 7 or later, if you have Bzlmod enabled, you can also fetch all
external dependencies by running
```posix-terminal theme={null}
bazel fetch
```
You do not need to run bazel fetch at all if you have all of the tools you are
using (from library jars to the JDK itself) under your workspace root.
However, if you're using anything outside of the workspace directory then Bazel
will automatically run `bazel fetch` before running
`bazel build`.
#### The repository cache
Bazel tries to avoid fetching the same file several times, even if the same
file is needed in different workspaces, or if the definition of an external
repository changed but it still needs the same file to download. To do so,
bazel caches all files downloaded in the repository cache which, by default,
is located at `~/.cache/bazel/_bazel_$USER/cache/repos/v1/`. The
location can be changed by the `--repository_cache` option. The
cache is shared between all workspaces and installed versions of bazel.
An entry is taken from the cache if
Bazel knows for sure that it has a copy of the correct file, that is, if the
download request has a SHA256 sum of the file specified and a file with that
hash is in the cache. So specifying a hash for each external file is
not only a good idea from a security perspective; it also helps avoiding
unnecessary downloads.
Upon each cache hit, the modification time of the file in the cache is
updated. In this way, the last use of a file in the cache directory can easily
be determined, for example to manually clean up the cache. The cache is never
cleaned up automatically, as it might contain a copy of a file that is no
longer available upstream.
#### \[Deprecated] Distribution files directories
**Deprecated**: *Using repository cache is preferred to achieve offline build.*
The distribution directory is another Bazel mechanism to avoid unnecessary
downloads. Bazel searches distribution directories before the repository cache.
The primary difference is that the distribution directory requires manual
preparation.
Using the
[`--distdir=/path/to-directory`](/reference/command-line-reference#flag--distdir)
option, you can specify additional read-only directories to look for files
instead of fetching them. A file is taken from such a directory if the file name
is equal to the base name of the URL and additionally the hash of the file is
equal to the one specified in the download request. This only works if the
file hash is specified in the repo rule declaration.
While the condition on the file name is not necessary for correctness, it
reduces the number of candidate files to one per specified directory. In this
way, specifying distribution files directories remains efficient, even if the
number of files in such a directory grows large.
#### Running Bazel in an airgapped environment
To keep Bazel's binary size small, Bazel's implicit dependencies are fetched
over the network while running for the first time. These implicit dependencies
contain toolchains and rules that may not be necessary for everyone. For
example, Android tools are unbundled and fetched only when building Android
projects.
However, these implicit dependencies may cause problems when running Bazel in an
airgapped environment, even if you have vendored all of your external
dependencies. To solve that, you can prepare a repository cache (with Bazel 7 or
later) or distribution directory (with Bazel prior to 7) containing these
dependencies on a machine with network access, and then transfer them to the
airgapped environment with an offline approach.
##### Repository cache (with Bazel 7 or later)
To prepare the [repository cache](#repository-cache), use the
[`--repository_cache`](/reference/command-line-reference#flag--repository_cache)
flag. You will need to do this once for every new Bazel binary version, since
the implicit dependencies can be different for every release.
To fetch those dependencies outside of your airgapped environment, first create
an empty workspace:
```posix-terminal theme={null}
mkdir empty_workspace && cd empty_workspace
touch MODULE.bazel
```
To fetch built-in Bzlmod dependencies, run
```posix-terminal theme={null}
bazel fetch --repository_cache="path/to/repository/cache"
```
If you still rely on the legacy WORKSPACE file, to fetch built-in WORKSPACE
dependencies, run
```posix-terminal theme={null}
bazel sync --repository_cache="path/to/repository/cache"
```
Finally, when you use Bazel in your airgapped environment, pass the same
`--repository_cache` flag. For convenience, you can add it as an `.bazelrc`
entry:
```python theme={null}
common --repository_cache="path/to/repository/cache"
```
In addition, you may also need to clone the
[BCR](https://github.com/bazelbuild/bazel-central-registry) locally and use
`--registry` flag to point your local copy to prevent Bazel from accessing the
BCR through internet. Add the following line to your `.bazelrc`:
```python theme={null}
common --registry="path/to/local/bcr/registry"
```
##### Distribution directory (with Bazel prior to 7)
To prepare the [distribution directory](#distribution-directory), use the
[`--distdir`](/reference/command-line-reference#flag--distdir)
flag. You will need to do this once for every new Bazel binary version, since
the implicit dependencies can be different for every release.
To build these dependencies outside of your airgapped environment, first
checkout the Bazel source tree at the right version:
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/bazel "$BAZEL_DIR"
cd "$BAZEL_DIR"
git checkout "$BAZEL_VERSION"
```
Then, build the tarball containing the implicit runtime dependencies for that
specific Bazel version:
```posix-terminal theme={null}
bazel build @additional_distfiles//:archives.tar
```
Export this tarball to a directory that can be copied into your airgapped
environment. Note the `--strip-components` flag, because `--distdir` can be
quite finicky with the directory nesting level:
```posix-terminal theme={null}
tar xvf bazel-bin/external/additional_distfiles/archives.tar \
-C "$NEW_DIRECTORY" --strip-components=3
```
Finally, when you use Bazel in your airgapped environment, pass the `--distdir`
flag pointing to the directory. For convenience, you can add it as an `.bazelrc`
entry:
```posix-terminal theme={null}
build --distdir=path/to/directory
```
### Build configurations and cross-compilation
All the inputs that specify the behavior and result of a given build can be
divided into two distinct categories. The first kind is the intrinsic
information stored in the `BUILD` files of your project: the build rule, the
values of its attributes, and the complete set of its transitive dependencies.
The second kind is the external or environmental data, supplied by the user or
by the build tool: the choice of target architecture, compilation and linking
options, and other toolchain configuration options. We refer to a complete set
of environmental data as a **configuration**.
In any given build, there may be more than one configuration. Consider a
cross-compile, in which you build a `//foo:bin` executable for a 64-bit
architecture, but your workstation is a 32-bit machine. Clearly, the build will
require building `//foo:bin` using a toolchain capable of creating 64-bit
executables, but the build system must also build various tools used during the
build itself—for example tools that are built from source, then subsequently
used in, say, a genrule—and these must be built to run on your workstation. Thus
we can identify two configurations: the **exec configuration**, which is used
for building tools that run during the build, and the **target configuration**
(or *request configuration*, but we say "target configuration" more often even
though that word already has many meanings), which is used for building the
binary you ultimately requested.
Typically, there are many libraries that are prerequisites of both the requested
build target (`//foo:bin`) and one or more of the exec tools, for example some
base libraries. Such libraries must be built twice, once for the exec
configuration, and once for the target configuration. Bazel takes care of
ensuring that both variants are built, and that the derived files are kept
separate to avoid interference; usually such targets can be built concurrently,
since they are independent of each other. If you see progress messages
indicating that a given target is being built twice, this is most likely the
explanation.
The exec configuration is derived from the target configuration as follows:
* Use the same version of Crosstool (`--crosstool_top`) as specified in the
request configuration, unless `--host_crosstool_top` is specified.
* Use the value of `--host_cpu` for `--cpu` (default: `k8`).
* Use the same values of these options as specified in the request
configuration: `--compiler`, `--use_ijars`, and if `--host_crosstool_top` is
used, then the value of `--host_cpu` is used to look up a
`default_toolchain` in the Crosstool (ignoring `--compiler`) for the exec
configuration.
* Use the value of `--host_javabase` for `--javabase`
* Use the value of `--host_java_toolchain` for `--java_toolchain`
* Use optimized builds for C++ code (`-c opt`).
* Generate no debugging information (`--copt=-g0`).
* Strip debug information from executables and shared libraries
(`--strip=always`).
* Place all derived files in a special location, distinct from that used by
any possible request configuration.
* Suppress stamping of binaries with build data (see `--embed_*` options).
* All other values remain at their defaults.
There are many reasons why it might be preferable to select a distinct exec
configuration from the request configuration. Most importantly:
Firstly, by using stripped, optimized binaries, you reduce the time spent
linking and executing the tools, the disk space occupied by the tools, and the
network I/O time in distributed builds.
Secondly, by decoupling the exec and request configurations in all builds, you
avoid very expensive rebuilds that would result from minor changes to the
request configuration (such as changing linker options does), as described
earlier.
### Correct incremental rebuilds
One of the primary goals of the Bazel project is to ensure correct incremental
rebuilds. Previous build tools, especially those based on Make, make several
unsound assumptions in their implementation of incremental builds.
Firstly, that timestamps of files increase monotonically. While this is the
typical case, it is very easy to fall afoul of this assumption; syncing to an
earlier revision of a file causes that file's modification time to decrease;
Make-based systems will not rebuild.
More generally, while Make detects changes to files, it does not detect changes
to commands. If you alter the options passed to the compiler in a given build
step, Make will not re-run the compiler, and it is necessary to manually discard
the invalid outputs of the previous build using `make clean`.
Also, Make is not robust against the unsuccessful termination of one of its
subprocesses after that subprocess has started writing to its output file. While
the current execution of Make will fail, the subsequent invocation of Make will
blindly assume that the truncated output file is valid (because it is newer than
its inputs), and it will not be rebuilt. Similarly, if the Make process is
killed, a similar situation can occur.
Bazel avoids these assumptions, and others. Bazel maintains a database of all
work previously done, and will only omit a build step if it finds that the set
of input files (and their timestamps) to that build step, and the compilation
command for that build step, exactly match one in the database, and, that the
set of output files (and their timestamps) for the database entry exactly match
the timestamps of the files on disk. Any change to the input files or output
files, or to the command itself, will cause re-execution of the build step.
The benefit to users of correct incremental builds is: less time wasted due to
confusion. (Also, less time spent waiting for rebuilds caused by use of `make
clean`, whether necessary or pre-emptive.)
#### Build consistency and incremental builds
Formally, we define the state of a build as *consistent* when all the expected
output files exist, and their contents are correct, as specified by the steps or
rules required to create them. When you edit a source file, the state of the
build is said to be *inconsistent*, and remains inconsistent until you next run
the build tool to successful completion. We describe this situation as *unstable
inconsistency*, because it is only temporary, and consistency is restored by
running the build tool.
There is another kind of inconsistency that is pernicious: *stable
inconsistency*. If the build reaches a stable inconsistent state, then repeated
successful invocation of the build tool does not restore consistency: the build
has gotten "stuck", and the outputs remain incorrect. Stable inconsistent states
are the main reason why users of Make (and other build tools) type `make clean`.
Discovering that the build tool has failed in this manner (and then recovering
from it) can be time consuming and very frustrating.
Conceptually, the simplest way to achieve a consistent build is to throw away
all the previous build outputs and start again: make every build a clean build.
This approach is obviously too time-consuming to be practical (except perhaps
for release engineers), and therefore to be useful, the build tool must be able
to perform incremental builds without compromising consistency.
Correct incremental dependency analysis is hard, and as described above, many
other build tools do a poor job of avoiding stable inconsistent states during
incremental builds. In contrast, Bazel offers the following guarantee: after a
successful invocation of the build tool during which you made no edits, the
build will be in a consistent state. (If you edit your source files during a
build, Bazel makes no guarantee about the consistency of the result of the
current build. But it does guarantee that the results of the *next* build will
restore consistency.)
As with all guarantees, there comes some fine print: there are some known ways
of getting into a stable inconsistent state with Bazel. We won't guarantee to
investigate such problems arising from deliberate attempts to find bugs in the
incremental dependency analysis, but we will investigate and do our best to fix
all stable inconsistent states arising from normal or "reasonable" use of the
build tool.
If you ever detect a stable inconsistent state with Bazel, please report a bug.
#### Sandboxed execution
Note: Sandboxing is enabled by default for local execution.
Bazel uses sandboxes to guarantee that actions run hermetically and
correctly. Bazel runs *spawns* (loosely speaking: actions) in sandboxes that
only contain the minimal set of files the tool requires to do its job. Currently
sandboxing works on Linux 3.12 or newer with the `CONFIG_USER_NS` option
enabled, and also on macOS 10.11 or newer.
Bazel will print a warning if your system does not support sandboxing to alert
you to the fact that builds are not guaranteed to be hermetic and might affect
the host system in unknown ways. To disable this warning you can pass the
`--ignore_unsupported_sandboxing` flag to Bazel.
Note: Hermeticity means that the action only uses its declared input
files and no other files in the filesystem, and it only produces its declared
output files. See [Hermeticity](/basics/hermeticity) for more details.
On some platforms such as [Google Kubernetes Engine](https://cloud.google.com/kubernetes-engine/) cluster nodes or Debian,
user namespaces are deactivated by default due to security
concerns. This can be checked by looking at the file
`/proc/sys/kernel/unprivileged_userns_clone`: if it exists and contains a 0,
then user namespaces can be activated with
`sudo sysctl kernel.unprivileged_userns_clone=1`.
In some cases, the Bazel sandbox fails to execute rules because of the system
setup. The symptom is generally a failure that output a message similar to
`namespace-sandbox.c:633: execvp(argv[0], argv): No such file or directory`.
In that case, try to deactivate the sandbox for genrules with
`--strategy=Genrule=standalone` and for other rules with
`--spawn_strategy=standalone`. Also please report a bug on our
issue tracker and mention which Linux distribution you're using so that we can
investigate and provide a fix in a subsequent release.
### Phases of a build
In Bazel, a build occurs in three distinct phases; as a user, understanding the
difference between them provides insight into the options which control a build
(see below).
#### Loading phase
The first is **loading** during which all the necessary BUILD files for the
initial targets, and their transitive closure of dependencies, are loaded,
parsed, evaluated and cached.
For the first build after a Bazel server is started, the loading phase typically
takes many seconds as many BUILD files are loaded from the file system. In
subsequent builds, especially if no BUILD files have changed, loading occurs
very quickly.
Errors reported during this phase include: package not found, target not found,
lexical and grammatical errors in a BUILD file, and evaluation errors.
#### Analysis phase
The second phase, **analysis**, involves the semantic analysis and validation of
each build rule, the construction of a build dependency graph, and the
determination of exactly what work is to be done in each step of the build.
Like loading, analysis also takes several seconds when computed in its entirety.
However, Bazel caches the dependency graph from one build to the next and only
reanalyzes what it has to, which can make incremental builds extremely fast in
the case where the packages haven't changed since the previous build.
Errors reported at this stage include: inappropriate dependencies, invalid
inputs to a rule, and all rule-specific error messages.
The loading and analysis phases are fast because Bazel avoids unnecessary file
I/O at this stage, reading only BUILD files in order to determine the work to be
done. This is by design, and makes Bazel a good foundation for analysis tools,
such as Bazel's [query](/query/guide) command, which is implemented atop the loading
phase.
#### Execution phase
The third and final phase of the build is **execution**. This phase ensures that
the outputs of each step in the build are consistent with its inputs, re-running
compilation/linking/etc. tools as necessary. This step is where the build spends
the majority of its time, ranging from a few seconds to over an hour for a large
build. Errors reported during this phase include: missing source files, errors
in a tool executed by some build action, or failure of a tool to produce the
expected set of outputs.
# Client/server implementation
Source: https://bazel.build/run/client-server
The Bazel system is implemented as a long-lived server process. This allows it
to perform many optimizations not possible with a batch-oriented implementation,
such as caching of BUILD files, dependency graphs, and other metadata from one
build to the next. This improves the speed of incremental builds, and allows
different commands, such as `build` and `query` to share the same cache of
loaded packages, making queries very fast. Each server can handle at most one
invocation at a time; further concurrent invocations will either block or
fail-fast (see `--block_for_lock`).
When you run `bazel`, you're running the client. The client finds the server
based on the [output base](/run/scripts#output-base-option), which by default is
determined by the path of the base workspace directory and your userid, so if
you build in multiple workspaces, you'll have multiple output bases and thus
multiple Bazel server processes. Multiple users on the same workstation can
build concurrently in the same workspace because their output bases will differ
(different userids).
If the client cannot find a running server instance, it starts a new one. It
does this by checking if the output base already exists, implying the blaze
archive has already been unpacked. Otherwise if the output base doesn't exist,
the client unzips the archive's files and sets their `mtime`s to a date 9 years
in the future. Once installed, the client confirms that the `mtime`s of the
unzipped files are equal to the far off date to ensure no installation tampering
has occurred.
The server process will stop after a period of inactivity (3 hours, by default,
which can be modified using the startup option `--max_idle_secs`). For the most
part, the fact that there is a server running is invisible to the user, but
sometimes it helps to bear this in mind. For example, if you're running scripts
that perform a lot of automated builds in different directories, it's important
to ensure that you don't accumulate a lot of idle servers; you can do this by
explicitly shutting them down when you're finished with them, or by specifying
a short timeout period.
### Managing memory pressure across multiple workspaces
Because each distinct workspace uses its own output base, working across multiple
repositories starts a dedicated Bazel server for each workspace. Even when idle,
each server process retains in-memory caches (such as the Skyframe dependency graph
and package representations) to keep subsequent incremental builds fast.
If your machine experiences memory pressure due to multiple idle servers, you can
configure global protection in your user-level `~/.bazelrc`:
* **Shut down automatically on low RAM:** Add `startup --shutdown_on_low_sys_mem`
to instruct servers idle for more than 5 minutes to exit when host RAM becomes
critically low (supported on Linux and macOS).
* **Reduce idle timeout:** Lower `startup --max_idle_secs=1800` (e.g. 30 minutes
instead of the 3-hour default) so unused servers terminate earlier.
* **Explicit shutdown:** Run `bazel shutdown` in workspaces you are done with.
The name of a Bazel server process appears in the output of `ps x` or `ps -e f`
as bazel(dirname), where *dirname* is the basename of the
directory enclosing the root of your workspace directory. For example:
```posix-terminal theme={null}
ps -e f
16143 ? Sl 3:00 bazel(src-johndoe2) -server -Djava.library.path=...
```
This makes it easier to find out which server process belongs to a given
workspace. (Beware that with certain other options to `ps`, Bazel server
processes may be named just `java`.) Bazel servers can be stopped using the
[shutdown](/docs/user-manual#shutdown) command.
When running `bazel`, the client first checks that the server is the appropriate
version; if not, the server is stopped and a new one started. This ensures that
the use of a long-running server process doesn't interfere with proper
versioning.
# Calling Bazel from scripts
Source: https://bazel.build/run/scripts
You can call Bazel from scripts to perform a build, run tests, or query
the dependency graph. Bazel has been designed to enable effective scripting, but
this section lists some details to bear in mind to make your scripts more
robust.
### Choosing the output base
The `--output_base` option controls where the Bazel process should write the
outputs of a build to, as well as various working files used internally by
Bazel, one of which is a lock that guards against concurrent mutation of the
output base by multiple Bazel processes.
Choosing the correct output base directory for your script depends on several
factors. If you need to put the build outputs in a specific location, this will
dictate the output base you need to use. If you are making a "read only" call to
Bazel (such as `bazel query`), the locking factors will be more important. In
particular, if you need to run multiple instances of your script concurrently,
you should be mindful that each Blaze server process can handle at most one
invocation [at a time](/run/client-server#clientserver-implementation).
Depending on your situation it may make sense for each instance of your script
to wait its turn, or it may make sense to use `--output_base` to run multiple
Blaze servers and use those.
If you use the default output base value, you will be contending for the same
lock used by the user's interactive Bazel commands. If the user issues
long-running commands such as builds, your script will have to wait for those
commands to complete before it can continue.
### Notes about server mode
By default, Bazel uses a long-running [server process](/run/client-server) as an
optimization. When running Bazel in a script, don't forget to call `shutdown`
when you're finished with the server, or, specify `--max_idle_secs=5` so that
idle servers shut themselves down promptly.
### What exit code will I get?
Bazel attempts to differentiate failures due to the source code under
consideration from external errors that prevent Bazel from executing properly.
Bazel execution can result in following exit codes:
**Exit Codes common to all commands:**
* `0` - Success
* `2` - Command Line Problem, Bad or Illegal flags or command combination, or
Bad Environment Variables. Your command line must be modified.
* `8` - Build Interrupted but we terminated with an orderly shutdown.
* `9` - The server lock is held and `--noblock_for_lock` was passed.
* `32` - External Environment Failure not on this machine.
* `33` - Bazel ran out of memory and crashed. You need to modify your command line.
* `34` - Remote execution, remote cache, or Build Event Service error.
* `35` - Reserved for Google-internal use.
* `36` - Local Environmental Issue, suspected permanent.
* `37` - Unhandled Exception / Internal Bazel Error.
* `38` - Transient error publishing results to the Build Event Service.
* `39` - Blobs required by Bazel are evicted from Remote Cache.
* `41-44` - Reserved for Google-internal use.
* `45` - Persistent error publishing results to the Build Event Service.
* `47` - Reserved for Google-internal use.
* `48` - External dependency error.
* `49` - Reserved for Google-internal use.
**Return codes for commands `bazel build`, `bazel test`:**
* `1` - Build failed.
* `3` - Build OK, but some tests failed or timed out.
* `4` - Build successful but no tests were found even though testing was
requested.
**For `bazel run`:**
* `1` - Build failed.
* If the build succeeds but the executed subprocess returns a non-zero exit
code it will be the exit code of the command as well.
**For `bazel query`:**
* `3` - Partial success, but the query encountered 1 or more errors in the
input BUILD file set and therefore the results of the operation are not 100%
reliable. This is likely due to a `--keep_going` option on the command line.
* `7` - Command failure.
Future Bazel versions may add additional exit codes, replacing generic failure
exit code `1` with a different non-zero value with a particular meaning.
However, all non-zero exit values will always constitute an error.
### Reading the .bazelrc file
By default, Bazel reads the [`.bazelrc` file](/run/bazelrc) from the base
workspace directory or the user's home directory. Whether or not this is
desirable is a choice for your script; if your script needs to be perfectly
hermetic (such as when doing release builds), you should disable reading the
.bazelrc file by using the option `--bazelrc=/dev/null`. If you want to perform
a build using the user's preferred settings, the default behavior is better.
### Command log
The Bazel output is also available in a command log file which you can find with
the following command:
```posix-terminal theme={null}
bazel info command_log
```
The command log file contains the interleaved stdout and stderr streams of the
most recent Bazel command. Note that running `bazel info` will overwrite the
contents of this file, since it then becomes the most recent Bazel command.
However, the location of the command log file will not change unless you change
the setting of the `--output_base` or `--output_user_root` options.
### Parsing output
The Bazel output is quite easy to parse for many purposes. Two options that may
be helpful for your script are `--noshow_progress` which suppresses progress
messages, and --show\_result n, which controls whether or
not "build up-to-date" messages are printed; these messages may be parsed to
discover which targets were successfully built, and the location of the output
files they created. Be sure to specify a very large value of *n* if you rely on
these messages.
## Troubleshooting performance by profiling
See the [Performance Profiling](/rules/performance#performance-profiling) section.
# Bazel Tutorial: Build an Android App
Source: https://bazel.build/start/android-app
**Note:** There are known limitations on using Bazel for building Android apps.
Visit the [rules\_android issues page](https://github.com/bazelbuild/rules_android/issues)
to see the list of known issues. While the Bazel team and Open Source Software
(OSS) contributors work actively to address known issues, users should be aware
that Android Studio does not officially support Bazel projects.
This tutorial covers how to build a simple Android app using Bazel.
Bazel supports building Android apps using the
[Android rules](/reference/be/android).
This tutorial is intended for Windows, macOS and Linux users and does not
require experience with Bazel or Android app development. You do not need to
write any Android code in this tutorial.
## What you'll learn
In this tutorial you learn how to:
* Set up your environment by installing Bazel and Android Studio, and
downloading the sample project.
* Set up a Bazel workspace that contains the source code
for the app and a `MODULE.bazel` file that identifies the top level of the
workspace directory.
* Update the `MODULE.bazel` file to contain references to the required
external dependencies, like the Android SDK.
* Create a `BUILD` file.
* Build the app with Bazel.
* Deploy and run the app on an Android emulator or physical device.
## Before you begin
### Install Bazel
Before you begin the tutorial, install the following software:
* **Bazel.** To install, follow the [installation instructions](/install).
* **Android Studio.** To install, follow the steps to [download Android Studio](https://developer.android.com/sdk/index.html).
Execute the setup wizard to download the SDK and configure your environment.
* (Optional) **Git.** Use `git` to download the Android app project.
### Get the sample project
For the sample project, use the tutorial Android app project in
[Bazel's examples repository](https://github.com/bazelbuild/examples/tree/main/android/tutorial).
This app has a single button that prints a greeting when clicked:
**Figure 1.** Android app button greeting.
Clone the repository with `git` (or [download the ZIP file directly](https://github.com/bazelbuild/examples/archive/master.zip)):
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/examples
```
The sample project for this tutorial is in `examples/android/tutorial`. For
the rest of the tutorial, you will be executing commands in this directory.
### Review the source files
Take a look at the source files for the app.
```
.
├── README.md
└── src
└── main
├── AndroidManifest.xml
└── java
└── com
└── example
└── bazel
├── AndroidManifest.xml
├── Greeter.java
├── MainActivity.java
└── res
├── layout
│ └── activity_main.xml
└── values
├── colors.xml
└── strings.xml
```
The key files and directories are:
| Name | Location |
| - | - |
| Android manifest files | `src/main/AndroidManifest.xml` and `src/main/java/com/example/bazel/AndroidManifest.xml` |
| Android source files | `src/main/java/com/example/bazel/MainActivity.java` and `Greeter.java` |
| Resource file directory | `src/main/java/com/example/bazel/res/` |
## Build with Bazel
### Set up the workspace
A [workspace](/concepts/build-ref#workspace) is a directory that contains the
source files for one or more software projects, and has a `MODULE.bazel` file at
its root.
The `MODULE.bazel` file may be empty or may contain references to [external dependencies](/external/overview) required to build your project.
First, run the following command to create an empty `MODULE.bazel` file:
| OS | Command |
| - | - |
| Linux, macOS | `touch MODULE.bazel` |
| Windows (Command Prompt) | `type nul > MODULE.bazel` |
| Windows (PowerShell) | `New-Item MODULE.bazel -ItemType file` |
### Running Bazel
You can now check if Bazel is running correctly with the command:
```posix-terminal theme={null}
bazel info workspace
```
If Bazel prints the path of the current directory, you're good to go! If the
`MODULE.bazel` file does not exist, you may see an error message like:
```
ERROR: The 'info' command is only supported from within a workspace.
```
### Integrate with the Android SDK
Bazel needs to run the Android SDK
[build tools](https://developer.android.com/tools/revisions/build-tools.html)
to build the app. This means that you need to add some information to your
`MODULE.bazel` file so that Bazel knows where to find them.
Add the following line to your `MODULE.bazel` file:
```python theme={null}
bazel_dep(name = "rules_android", version = "0.6.6")
remote_android_extensions = use_extension(
"@rules_android//bzlmod_extensions:android_extensions.bzl",
"remote_android_tools_extensions")
use_repo(remote_android_extensions, "android_tools")
android_sdk_repository_extension = use_extension("@rules_android//rules/android_sdk_repository:rule.bzl", "android_sdk_repository_extension")
use_repo(android_sdk_repository_extension, "androidsdk")
```
This will use the Android SDK at the path referenced by the `ANDROID_HOME`
environment variable, and automatically detect the highest API level and the
latest version of build tools installed within that location.
You can set the `ANDROID_HOME` variable to the location of the Android SDK. Find
the path to the installed SDK using Android Studio's [SDK Manager](https://developer.android.com/studio/intro/update#sdk-manager).
Assuming the SDK is installed to default locations, you can use the following
commands to set the `ANDROID_HOME` variable:
| OS | Command |
| - | - |
| Linux | `export ANDROID_HOME=$HOME/Android/Sdk/` |
| macOS | `export ANDROID_HOME=$HOME/Library/Android/sdk` |
| Windows (Command Prompt) | `set ANDROID_HOME=%LOCALAPPDATA%\Android\Sdk` |
| Windows (PowerShell) | `$env:ANDROID_HOME="$env:LOCALAPPDATA\Android\Sdk"` |
The above commands set the variable only for the current shell session. To make
them permanent, run the following commands:
| OS | Command |
| - | - |
| Linux | `echo "export ANDROID_HOME=$HOME/Android/Sdk/" >> ~/.bashrc` |
| macOS | `echo "export ANDROID_HOME=$HOME/Library/Android/Sdk/" >> ~/.bashrc` |
| Windows (Command Prompt) | `setx ANDROID_HOME "%LOCALAPPDATA%\Android\Sdk"` |
| Windows (PowerShell) | `[System.Environment]::SetEnvironmentVariable('ANDROID_HOME', "$env:LOCALAPPDATA\Android\Sdk", [System.EnvironmentVariableTarget]::User)` |
**Optional:** If you want to compile native code into your Android app, you
also need to download the [Android NDK](https://developer.android.com/ndk/downloads/index.html)
and use `rules_android_ndk` by adding the following line to your `MODULE.bazel` file:
```python theme={null}
bazel_dep(name = "rules_android_ndk", version = "0.1.3")
```
For more information, read [Using the Android Native Development Kit with Bazel](/docs/android-ndk).
It's not necessary to set the API levels to the same value for the SDK and NDK.
[This page](https://developer.android.com/ndk/guides/stable_apis.html)
contains a map from Android releases to NDK-supported API levels.
### Create a BUILD file
A [`BUILD` file](/concepts/build-files) describes the relationship
between a set of build outputs, like compiled Android resources from `aapt` or
class files from `javac`, and their dependencies. These dependencies may be
source files (Java, C++) in your workspace or other build outputs. `BUILD` files
are written in a language called **Starlark**.
`BUILD` files are part of a concept in Bazel known as the *package hierarchy*.
The package hierarchy is a logical structure that overlays the directory
structure in your workspace. Each [package](/concepts/build-ref#packages) is a
directory (and its subdirectories) that contains a related set of source files
and a `BUILD` file. The package also includes any subdirectories, excluding
those that contain their own `BUILD` file. The *package name* is the path to the
`BUILD` file relative to the `MODULE.bazel` file.
Note that Bazel's package hierarchy is conceptually different from the Java
package hierarchy of your Android App directory where the `BUILD` file is
located, although the directories may be organized identically.
For the simple Android app in this tutorial, the source files in `src/main/`
comprise a single Bazel package. A more complex project may have many nested
packages.
#### Add an android\_library rule
A `BUILD` file contains several different types of declarations for Bazel. The
most important type is the
[build rule](/concepts/build-files#types-of-build-rules), which tells
Bazel how to build an intermediate or final software output from a set of source
files or other dependencies. Bazel provides two build rules,
[`android_library`](/reference/be/android#android_library) and
[`android_binary`](/reference/be/android#android_binary), that you can use to
build an Android app.
For this tutorial, you'll first use the
`android_library` rule to tell Bazel to build an [Android library module](http://developer.android.com/tools/projects/index.html#LibraryProjects)
from the app source code and resource files. You'll then use the
`android_binary` rule to tell Bazel how to build the Android application package.
Create a new `BUILD` file in the `src/main/java/com/example/bazel` directory,
and declare a new `android_library` target:
`src/main/java/com/example/bazel/BUILD`:
```python theme={null}
load("@rules_android//rules:rules.bzl", "android_library")
package(
default_visibility = ["//src:__subpackages__"],
)
android_library(
name = "greeter_activity",
srcs = [
"Greeter.java",
"MainActivity.java",
],
manifest = "AndroidManifest.xml",
resource_files = glob(["res/**"]),
)
```
The `android_library` build rule contains a set of attributes that specify the
information that Bazel needs to build a library module from the source files.
Note also that the name of the rule is `greeter_activity`. You'll reference the
rule using this name as a dependency in the `android_binary` rule.
#### Add an android\_binary rule
The [`android_binary`](/reference/be/android#android_binary) rule builds
the Android application package (`.apk` file) for your app.
Create a new `BUILD` file in the `src/main/` directory,
and declare a new `android_binary` target:
`src/main/BUILD`:
```python theme={null}
load("@rules_android//rules:rules.bzl", "android_binary")
android_binary(
name = "app",
manifest = "//src/main/java/com/example/bazel:AndroidManifest.xml",
deps = ["//src/main/java/com/example/bazel:greeter_activity"],
)
```
Here, the `deps` attribute references the output of the `greeter_activity` rule
you added to the `BUILD` file above. This means that when Bazel builds the
output of this rule it checks first to see if the output of the
`greeter_activity` library rule has been built and is up-to-date. If not, Bazel
builds it and then uses that output to build the application package file.
Now, save and close the file.
### Build the app
Try building the app! Run the following command to build the
`android_binary` target:
```posix-terminal theme={null}
bazel build //src/main:app
```
The [`build`](/docs/user-manual#build) subcommand instructs Bazel to build the
target that follows. The target is specified as the name of a build rule inside
a `BUILD` file, with along with the package path relative to your workspace
directory. For this example, the target is `app` and the package path is
`//src/main/`.
Note that you can sometimes omit the package path or target name, depending on
your current working directory at the command line and the name of the target.
For more details about target labels and paths, see [Labels](/concepts/labels).
Bazel will start to build the sample app. During the build process, its output
will appear similar to the following:
```bash theme={null}
INFO: Analysed target //src/main:app (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //src/main:app up-to-date:
bazel-bin/src/main/app_deploy.jar
bazel-bin/src/main/app_unsigned.apk
bazel-bin/src/main/app.apk
```
#### Locate the build outputs
Bazel puts the outputs of both intermediate and final build operations in a set
of per-user, per-workspace output directories. These directories are symlinked
from the following locations at the top-level of the project directory, where
the `MODULE.bazel` file is:
* `bazel-bin` stores binary executables and other runnable build outputs
* `bazel-genfiles` stores intermediary source files that are generated by
Bazel rules
* `bazel-out` stores other types of build outputs
Bazel stores the Android `.apk` file generated using the `android_binary` rule
in the `bazel-bin/src/main` directory, where the subdirectory name `src/main` is
derived from the name of the Bazel package.
At a command prompt, list the contents of this directory and find the `app.apk`
file:
| OS | Command |
| - | - |
| Linux, macOS | `ls bazel-bin/src/main` |
| Windows (Command Prompt) | `dir bazel-bin\src\main` |
| Windows (PowerShell) | `ls bazel-bin\src\main` |
### Run the app
You can now deploy the app to a connected Android device or emulator from the
command line using `bazel mobile-install`.
This command uses the Android Debug Bridge (`adb`) to communicate with the
device. You must set up your device to use `adb` following the instructions in
[Android Debug Bridge](http://developer.android.com/tools/help/adb.html)
before deployment. You can also choose to install the app on the Android emulator
included in Android Studio. Make sure the emulator is running before executing
the command below.
Enter the following:
```posix-terminal theme={null}
bazel mobile-install //src/main:app \
--mode=skylark \
--mobile_install_aspect=@rules_android//mobile_install:mi.bzl \
--mobile_install_supported_rules=android_binary \
--java_runtime_version=17 \
--java_language_version=17 \
--tool_java_runtime_version=17 \
--tool_java_language_version=17
```
Note that the extra flags required for mobile-install can be added to your
project's [bazelrc file](/run/bazelrc). The mobile-install-specific flags
(`--mode`, `--mobile_install*`) will no longer be required starting from
Bazel 8.4.0 and onwards. The various Java flags for language and runtime version
may be required depending on your workspace's Java configuration.
*Mobile-install sub-tools require a language and runtime level of 17 or higher.*
Now the "Bazel Tutorial App" should install and launch automatically:
**Figure 2.** Bazel tutorial app.
**Congratulations! You have just installed your first Bazel-built Android app.**
## Further reading
For more details, see these pages:
* Open issues on [rules\_android GitHub](https://github.com/bazelbuild/rules_android/issues)
* More information on [mobile-install](/docs/mobile-install)
* Shrink and optimize your app with [R8](https://github.com/bazelbuild/rules_android/tree/main/docs/r8-optimization.md)
* Integrate external dependencies like AppCompat, Guava and JUnit from Maven
repositories using [rules\_jvm\_external](https://github.com/bazelbuild/rules_jvm_external)
* Run Robolectric tests with the [robolectric-bazel](https://github.com/robolectric/robolectric-bazel)
integration.
* Integrating C and C++ code into your Android app with the [NDK](/docs/android-ndk)
* See more Bazel example projects of:
* [a Kotlin app](https://github.com/bazelbuild/rules_jvm_external/tree/master/examples/android_kotlin_app)
* [Robolectric testing](https://github.com/bazelbuild/rules_jvm_external/tree/master/examples/android_local_test)
* [Espresso testing](https://github.com/bazelbuild/rules_jvm_external/tree/master/examples/android_instrumentation_test)
Happy building!
# Bazel Tutorial: Build a C++ Project
Source: https://bazel.build/start/cpp
## Introduction
New to Bazel? You're in the right place. Follow this First Build tutorial for a
simplified introduction to using Bazel. This tutorial defines key terms as they
are used in Bazel's context and walks you through the basics of the Bazel
workflow. Starting with the tools you need, you will build and run three
projects with increasing complexity and learn how and why they get more complex.
While Bazel is a [build system](https://bazel.build/basics/build-systems) that
supports multi-language builds, this tutorial uses a C++ project as an example
and provides the general guidelines and flow that apply to most languages.
Estimated completion time: 30 minutes.
### Prerequisites
Start by [installing Bazel](https://bazel.build/install), if you haven't
already. This tutorial uses Git for source control, so for best results [install Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) as well.
Next, retrieve the sample project from Bazel's GitHub repository by running the
following in your command-line tool of choice:
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/examples
```
The sample project for this tutorial is in the `examples/cpp-tutorial`
directory.
Take a look at how it's structured:
```none theme={null}
examples
└── cpp-tutorial
├──stage1
│ ├── main
│ │ ├── BUILD
│ │ └── hello-world.cc
│ └── MODULE.bazel
├──stage2
│ ├── main
│ │ ├── BUILD
│ │ ├── hello-world.cc
│ │ ├── hello-greet.cc
│ │ └── hello-greet.h
│ └── MODULE.bazel
└──stage3
├── main
│ ├── BUILD
│ ├── hello-world.cc
│ ├── hello-greet.cc
│ └── hello-greet.h
├── lib
│ ├── BUILD
│ ├── hello-time.cc
│ └── hello-time.h
└── MODULE.bazel
```
There are three sets of files, each set representing a stage in this tutorial.
In the first stage, you will build a single [target](https://bazel.build/reference/glossary#target) residing in a single [package](https://bazel.build/reference/glossary#package). In the second stage, you will
build both a binary and a library from a single package. In the third and final
stage, you will build a project with multiple packages and build it with
multiple targets.
### Summary: Introduction
By installing Bazel (and Git) and cloning the repository for this tutorial, you
have laid the foundation for your first build with Bazel. Continue to the next
section to define some terms and set up your
[workspace](https://bazel.build/reference/glossary#workspace).
## Getting started
Before you can build a project, you need to set up its workspace. A workspace
is a directory that holds your project's source files and Bazel's build outputs.
It also contains these significant files:
* The `MODULE.bazel` file, which identifies the directory and its contents as
a Bazel workspace and lives at the root of the project's directory
structure. It's also where you specify your external dependencies.
* One or more [`BUILD` files](https://bazel.build/reference/glossary#build-file), which tell Bazel
how to build different parts of the project. A directory within the
workspace that contains a `BUILD` file is a
[package](https://bazel.build/reference/glossary#package). (More on packages
later in this tutorial.)
In future projects, to designate a directory as a Bazel workspace, create an
empty file named `MODULE.bazel` in that directory. For the purposes of this
tutorial, a `MODULE.bazel` file is already present in each stage.
### Understand the BUILD file
A `BUILD` file contains several different types of instructions for Bazel. Each
`BUILD` file requires at least one
[rule](https://bazel.build/reference/glossary#rule) as a set of instructions,
which tells Bazel how to build the outputs you want, such as executable binaries
or libraries. Each instance of a build rule in the `BUILD` file is called a
[target](https://bazel.build/reference/glossary#target) and points to a specific
set of source files and
[dependencies](https://bazel.build/reference/glossary#dependency). A target can
also point to other targets.
Take a look at the `BUILD` file in the `cpp-tutorial/stage1/main` directory:
```bazel theme={null}
cc_binary(
name = "hello-world",
srcs = ["hello-world.cc"],
)
```
In our example, the `hello-world` target instantiates Bazel's built-in
[`cc_binary` rule](https://bazel.build/reference/be/c-cpp#cc_binary). The rule
tells Bazel to build a self-contained executable binary from the
`hello-world.cc` source file with no dependencies.
### Summary: getting started
Now you are familiar with some key terms, and what they mean in the context of
this project and Bazel in general. In the next section, you will build and test
Stage 1 of the project.
## Stage 1: single target, single package
It's time to build the first part of the project. For a visual reference, the
structure of the Stage 1 section of the project is:
```none theme={null}
examples
└── cpp-tutorial
└──stage1
├── main
│ ├── BUILD
│ └── hello-world.cc
└── MODULE.bazel
```
Run the following to move to the `cpp-tutorial/stage1` directory:
```posix-terminal theme={null}
cd cpp-tutorial/stage1
```
Next, run:
```posix-terminal theme={null}
bazel build //main:hello-world
```
In the target label, the `//main:` part is the location of the `BUILD` file
relative to the root of the workspace, and `hello-world` is the target name in
the `BUILD` file.
Bazel produces something that looks like this:
```none theme={null}
INFO: Found 1 target...
Target //main:hello-world up-to-date:
bazel-bin/main/hello-world
INFO: Elapsed time: 2.267s, Critical Path: 0.25s
```
You just built your first Bazel target. Bazel places build outputs in the
`bazel-bin` directory at the root of the workspace.
Now test your freshly built binary, which is:
```posix-terminal theme={null}
bazel-bin/main/hello-world
```
This results in a printed "`Hello world`" message.
Here's the dependency graph of Stage 1:
### Summary: stage 1
Now that you have completed your first build, you have a basic idea of how a
build is structured. In the next stage, you will add complexity by adding
another target.
## Stage 2: multiple build targets
While a single target is sufficient for small projects, you may want to split
larger projects into multiple targets and packages. This allows for fast
incremental builds – that is, Bazel only rebuilds what's changed – and speeds up
your builds by building multiple parts of a project at once. This stage of the
tutorial adds a target, and the next adds a package.
This is the directory you are working with for Stage 2:
```none theme={null}
├──stage2
│ ├── main
│ │ ├── BUILD
│ │ ├── hello-world.cc
│ │ ├── hello-greet.cc
│ │ └── hello-greet.h
│ └── MODULE.bazel
```
Take a look at the `BUILD` file in the `cpp-tutorial/stage2/main` directory:
```bazel theme={null}
cc_library(
name = "hello-greet",
srcs = ["hello-greet.cc"],
hdrs = ["hello-greet.h"],
)
cc_binary(
name = "hello-world",
srcs = ["hello-world.cc"],
deps = [
":hello-greet",
],
)
```
With this `BUILD` file, Bazel first builds the `hello-greet` library (using
Bazel's built-in [`cc_library` rule](https://bazel.build/reference/be/c-cpp#cc_library)), then the
`hello-world` binary. The `deps` attribute in the `hello-world` target tells
Bazel that the `hello-greet` library is required to build the `hello-world`
binary.
Before you can build this new version of the project, you need to change
directories, switching to the `cpp-tutorial/stage2` directory by running:
```posix-terminal theme={null}
cd ../stage2
```
Now you can build the new binary using the following familiar command:
```posix-terminal theme={null}
bazel build //main:hello-world
```
Once again, Bazel produces something that looks like this:
```none theme={null}
INFO: Found 1 target...
Target //main:hello-world up-to-date:
bazel-bin/main/hello-world
INFO: Elapsed time: 2.399s, Critical Path: 0.30s
```
Now you can test your freshly built binary, which returns another "`Hello
world`":
```posix-terminal theme={null}
bazel-bin/main/hello-world
```
If you now modify `hello-greet.cc` and rebuild the project, Bazel only
recompiles that file.
Looking at the dependency graph, you can see that `hello-world` depends on an
extra input named `hello-greet`:
### Summary: stage 2
You've now built the project with two targets. The `hello-world` target builds
one source file and depends on one other target (`//main:hello-greet`), which
builds two additional source files. In the next section, take it a step further
and add another package.
## Stage 3: multiple packages
This next stage adds another layer of complication and builds a project with
multiple packages. Take a look at the structure and contents of the
`cpp-tutorial/stage3` directory:
```none theme={null}
└──stage3
├── main
│ ├── BUILD
│ ├── hello-world.cc
│ ├── hello-greet.cc
│ └── hello-greet.h
├── lib
│ ├── BUILD
│ ├── hello-time.cc
│ └── hello-time.h
└── MODULE.bazel
```
You can see that now there are two sub-directories, and each contains a `BUILD`
file. Therefore, to Bazel, the workspace now contains two packages: `lib` and
`main`.
Take a look at the `lib/BUILD` file:
```bazel theme={null}
cc_library(
name = "hello-time",
srcs = ["hello-time.cc"],
hdrs = ["hello-time.h"],
visibility = ["//main:__pkg__"],
)
```
And at the `main/BUILD` file:
```bazel theme={null}
cc_library(
name = "hello-greet",
srcs = ["hello-greet.cc"],
hdrs = ["hello-greet.h"],
)
cc_binary(
name = "hello-world",
srcs = ["hello-world.cc"],
deps = [
":hello-greet",
"//lib:hello-time",
],
)
```
The `hello-world` target in the main package depends on the` hello-time` target
in the `lib` package (hence the target label `//lib:hello-time`) - Bazel knows
this through the `deps` attribute. You can see this reflected in the dependency
graph:
For the build to succeed, you make the `//lib:hello-time` target in `lib/BUILD`
explicitly visible to targets in `main/BUILD` using the visibility attribute.
This is because by default targets are only visible to other targets in the same
`BUILD` file. Bazel uses target visibility to prevent issues such as libraries
containing implementation details leaking into public APIs.
Now build this final version of the project. Switch to the `cpp-tutorial/stage3`
directory by running:
```posix-terminal theme={null}
cd ../stage3
```
Once again, run the following command:
```posix-terminal theme={null}
bazel build //main:hello-world
```
Bazel produces something that looks like this:
```none theme={null}
INFO: Found 1 target...
Target //main:hello-world up-to-date:
bazel-bin/main/hello-world
INFO: Elapsed time: 0.167s, Critical Path: 0.00s
```
Now test the last binary of this tutorial for a final `Hello world` message:
```posix-terminal theme={null}
bazel-bin/main/hello-world
```
### Summary: stage 3
You've now built the project as two packages with three targets and understood
the dependencies between them, which equips you to go forth and build future
projects with Bazel. In the next section, take a look at how to continue your
Bazel journey.
## Next steps
You've now completed your first basic build with Bazel, but this is just the
start. Here are some more resources to continue learning with Bazel:
* To keep focusing on C++, read about common [C++ build use cases](https://bazel.build/tutorials/cpp-use-cases).
* To get started with building other applications with Bazel, see the
tutorials for [Java](https://bazel.build/start/java), [Android application](https://bazel.build/start/android-app), or [iOS application](https://bazel.build/start/ios-app).
* To learn more about working with local and remote repositories, read about
[external dependencies](https://bazel.build/docs/external).
* To learn more about Bazel's other rules, see this [reference guide](https://bazel.build/rules).
Happy building!
# Bazel Tutorial: Build a Go Project
Source: https://bazel.build/start/go
This tutorial introduces you to the basics of Bazel by showing you how to build
a Go (Golang) project. You'll learn how to set up your workspace, build a small
program, import a library, and run its test. Along the way, you'll learn key
Bazel concepts, such as targets and `BUILD` files.
Estimated completion time: 30 minutes
## Before you begin
### Install Bazel
Before you get started, first [install bazel](/install) if you haven't done so
already.
You can check if Bazel is installed by running `bazel version` in any directory.
### Install Go (optional)
You don't need to [install Go](https://go.dev/doc/install) to build Go projects
with Bazel. The Bazel Go rule set automatically downloads and uses a Go
toolchain instead of using the toolchain installed on your machine. This ensures
all developers on a project build with same version of Go.
However, you may still want to install a Go toolchain to run commands like `go
get` and `go mod tidy`.
You can check if Go is installed by running `go version` in any directory.
### Get the sample project
The Bazel examples are stored in a Git repository, so you'll need to [install Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) if you
haven't already. To download the examples repository, run this command:
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/examples
```
The sample project for this tutorial is in the `examples/go-tutorial` directory.
See what it contains:
```none theme={null}
go-tutorial/
└── stage1
└── stage2
└── stage3
```
There are three subdirectories (`stage1`, `stage2`, and `stage3`), each for a
different section of this tutorial. Each stage builds on the previous one.
## Build with Bazel
Start in the `stage1` directory, where we'll find a program. We can
build it with `bazel build`, then run it:
```posix-shell theme={null}
$ cd go-tutorial/stage1/
$ bazel build //:hello
INFO: Analyzed target //:hello (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //:hello up-to-date:
bazel-bin/hello_/hello
INFO: Elapsed time: 0.473s, Critical Path: 0.25s
INFO: 3 processes: 1 internal, 2 darwin-sandbox.
INFO: Build completed successfully, 3 total actions
$ bazel-bin/hello_/hello
Hello, Bazel! 💚
```
We can also build run the program with a single `bazel run` command:
```posix-shell theme={null}
$ bazel run //:hello
bazel run //:hello
INFO: Analyzed target //:hello (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //:hello up-to-date:
bazel-bin/hello_/hello
INFO: Elapsed time: 0.128s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
INFO: Running command line: bazel-bin/hello_/hello
Hello, Bazel! 💚
```
### Understanding project structure
Take a look at the project we just built.
`hello.go` contains the Go source code for the program.
```go theme={null}
package main
import "fmt"
func main() {
fmt.Println("Hello, Bazel! 💚")
}
```
`BUILD` contains some instructions for Bazel, telling it what we want to build.
You'll typically write a file like this in each directory. For this project, we
have a single `go_binary` target that builds our program from `hello.go`.
```bazel theme={null}
load("@rules_go//go:def.bzl", "go_binary")
go_binary(
name = "hello",
srcs = ["hello.go"],
)
```
`MODULE.bazel` tracks your project's dependencies. It also marks your project's
root directory, so you'll only write one `MODULE.bazel` file per project. It
serves a similar purpose to Go's `go.mod` file. You don't actually need a
`go.mod` file in a Bazel project, but it may still be useful to have one so that
you can continue using `go get` and `go mod tidy` for dependency management. The
Bazel Go rule set can import dependencies from `go.mod`, but we'll cover that in
another tutorial.
Our `MODULE.bazel` file contains a single dependency on
[rules\_go](https://github.com/bazel-contrib/rules_go), the Go rule set. We need
this dependency because Bazel doesn't have built-in support for Go.
```bazel theme={null}
bazel_dep(
name = "rules_go",
version = "0.50.1",
)
```
Finally, `MODULE.bazel.lock` is a file generated by Bazel that contains hashes
and other metadata about our dependencies. It includes implicit dependencies
added by Bazel itself, so it's quite long, and we won't show it here. Just like
`go.sum`, you should commit your `MODULE.bazel.lock` file to source control to
ensure everyone on your project gets the same version of each dependency. You
shouldn't need to edit `MODULE.bazel.lock` manually.
### Understand the BUILD file
Most of your interaction with Bazel will be through `BUILD` files (or
equivalently, `BUILD.bazel` files), so it's important to understand what they
do.
`BUILD` files are written in a scripting language called
[Starlark](https://bazel.build/rules/language), a limited subset of Python.
A `BUILD` file contains a list of
[targets](https://bazel.build/reference/glossary#target). A target is something
Bazel can build, like a binary, library, or test.
A target calls a rule function with a list of
[attributes](https://bazel.build/reference/glossary#attribute) to describe what
should be built. Our example has two attributes: `name` identifies the target on
the command line, and `srcs` is a list of source file paths (slash-separated,
relative to the directory containing the `BUILD` file).
A [rule](https://bazel.build/reference/glossary#rule) tells Bazel how to build a
target. In our example, we used the
[`go_binary`](https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/rules.md#go_binary)
rule. Each rule defines [actions](https://bazel.build/reference/glossary#action)
(commands) that generate a set of output files. For example, `go_binary` defines
Go compile and link actions that produce an executable output file.
Bazel has built-in rules for a few languages like Java and C++. You can find
their [documentation in the Build Encyclopedia](https://bazel.build/reference/be/overview#rules). You can find
rule sets for many other languages and tools on the [Bazel Central Registry (BCR)](https://registry.bazel.build/).
## Add a library
Move onto the `stage2` directory, where we'll build a new program that
prints your fortune. This program uses a separate Go package as a library that
selects a fortune from a predefined list of messages.
```none theme={null}
go-tutorial/stage2
├── BUILD
├── MODULE.bazel
├── MODULE.bazel.lock
├── fortune
│ ├── BUILD
│ └── fortune.go
└── print_fortune.go
```
`fortune.go` is the source file for the library. The `fortune` library is a
separate Go package, so its source files are in a separate directory. Bazel
doesn't require you to keep Go packages in separate directories, but it's a
strong convention in the Go ecosystem, and following it will help you stay
compatible with other Go tools.
```go theme={null}
package fortune
import "math/rand"
var fortunes = []string{
"Your build will complete quickly.",
"Your dependencies will be free of bugs.",
"Your tests will pass.",
}
func Get() string {
return fortunes[rand.Intn(len(fortunes))]
}
```
The `fortune` directory has its own `BUILD` file that tells Bazel how to build
this package. We use `go_library` here instead of `go_binary`.
We also need to set the `importpath` attribute to a string with which the
library can be imported into other Go source files. This name should be the
repository path (or module path) concatenated with the directory within the
repository.
Finally, we need to set the `visibility` attribute to `["//visibility:public"]`.
[`visibility`](https://bazel.build/concepts/visibility) may be set on any
target. It determines which Bazel packages may depend on this target. In our
case, we want any target to be able to depend on this library, so we use the
special value `//visibility:public`.
```bazel theme={null}
load("@rules_go//go:def.bzl", "go_library")
go_library(
name = "fortune",
srcs = ["fortune.go"],
importpath = "github.com/bazelbuild/examples/go-tutorial/stage2/fortune",
visibility = ["//visibility:public"],
)
```
You can build this library with:
```posix-shell theme={null}
$ bazel build //fortune
```
Next, see how `print_fortune.go` uses this package.
```go theme={null}
package main
import (
"fmt"
"github.com/bazelbuild/examples/go-tutorial/stage2/fortune"
)
func main() {
fmt.Println(fortune.Get())
}
```
`print_fortune.go` imports the package using the same string declared in the
`importpath` attribute of the `fortune` library.
We also need to declare this dependency to Bazel. Here's the `BUILD` file in the
`stage2` directory.
```bazel theme={null}
load("@rules_go//go:def.bzl", "go_binary")
go_binary(
name = "print_fortune",
srcs = ["print_fortune.go"],
deps = ["//fortune"],
)
```
You can run this with the command below.
```posix-shell theme={null}
bazel run //:print_fortune
```
The `print_fortune` target has a `deps` attribute, a list of other targets that
it depends on. It contains `"//fortune"`, a label string referring to the target
in the `fortune` directory named `fortune`.
Bazel requires that all targets declare their dependencies explicitly with
attributes like `deps`. This may seem cumbersome since dependencies are *also*
specified in source files, but Bazel's explictness gives it an advantage. Bazel
builds an [action graph](https://bazel.build/reference/glossary#action-graph)
containing all commands, inputs, and outputs before running any commands,
without reading any source files. Bazel can then cache action results or send
actions for [remote execution](https://bazel.build/remote/rbe) without built-in
language-specific logic.
### Understanding labels
A [label](https://bazel.build/reference/glossary#label) is a string Bazel uses
to identify a target or a file. Labels are used in command line arguments and in
`BUILD` file attributes like `deps`. We've seen a few already, like `//fortune`,
`//:print-fortune`, and `@rules_go//go:def.bzl`.
A label has three parts: a repository name, a package name, and a target (or
file) name.
The repository name is written between `@` and `//` and is used to refer to a
target from a different Bazel module (for historical reasons, *module* and
*repository* are sometimes used synonymously). In the label,
`@rules_go//go:def.bzl`, the repository name is `rules_go`. The repository name
can be omitted when referring to targets in the same repository.
The package name is written between `//` and `:` and is used to refer to a
target in from a different Bazel package. In the label `@rules_go//go:def.bzl`,
the package name is `go`. A Bazel
[package](https://bazel.build/reference/glossary#package) is a set of files and
targets defined by a `BUILD` or `BUILD.bazel` file in its top-level directory.
Its package name is a slash-separated path from the module root directory
(containing `MODULE.bazel`) to the directory containing the `BUILD` file. A
package may include subdirectories, but only if they don't also contain `BUILD`
files defining their own packages.
Most Go projects have one `BUILD` file per directory and one Go package per
`BUILD` file. The package name in a label may be omitted when referring to
targets in the same directory.
The target name is written after `:` and refers to a target within a package.
The target name may be omitted if it's the same as the last component of the
package name (so `//a/b/c:c` is the same as `//a/b/c`; `//fortune:fortune` is
the same as `//fortune`).
On the command-line, you can use `...` as a wildcard to refer to all the targets
within a package. This is useful for building or testing all the targets in a
repository.
```posix-shell theme={null}
# Build everything
$ bazel build //...
```
## Test your project
Next, move to the `stage3` directory, where we'll add a test.
```none theme={null}
go-tutorial/stage3
├── BUILD
├── MODULE.bazel
├── MODULE.bazel.lock
├── fortune
│ ├── BUILD
│ ├── fortune.go
│ └── fortune_test.go
└── print-fortune.go
```
`fortune/fortune_test.go` is our new test source file.
```go theme={null}
package fortune
import (
"slices"
"testing"
)
// TestGet checks that Get returns one of the strings from fortunes.
func TestGet(t *testing.T) {
msg := Get()
if i := slices.Index(fortunes, msg); i < 0 {
t.Errorf("Get returned %q, not one the expected messages", msg)
}
}
```
This file uses the unexported `fortunes` variable, so it needs to be compiled
into the same Go package as `fortune.go`. Look at the `BUILD` file to see
how that works:
```bazel theme={null}
load("@rules_go//go:def.bzl", "go_library", "go_test")
go_library(
name = "fortune",
srcs = ["fortune.go"],
importpath = "github.com/bazelbuild/examples/go-tutorial/stage3/fortune",
visibility = ["//visibility:public"],
)
go_test(
name = "fortune_test",
srcs = ["fortune_test.go"],
embed = [":fortune"],
)
```
We have a new `fortune_test` target that uses the `go_test` rule to compile and
link a test executable. `go_test` needs to compile `fortune.go` and
`fortune_test.go` together with the same command, so we use the `embed`
attribute here to incorporate the attributes of the `fortune` target into
`fortune_test`. `embed` is most commonly used with `go_test` and `go_binary`,
but it also works with `go_library`, which is sometimes useful for generated
code.
You may be wondering if the `embed` attribute is related to Go's
[`embed`](https://pkg.go.dev/embed) package, which is used to access data files
copied into an executable. This is an unfortunate name collision: rules\_go's
`embed` attribute was introduced before Go's `embed` package. Instead, rules\_go
uses the `embedsrcs` to list files that can be loaded with the `embed` package.
Try running our test with `bazel test`:
```posix-shell theme={null}
$ bazel test //fortune:fortune_test
INFO: Analyzed target //fortune:fortune_test (0 packages loaded, 0 targets configured).
INFO: Found 1 test target...
Target //fortune:fortune_test up-to-date:
bazel-bin/fortune/fortune_test_/fortune_test
INFO: Elapsed time: 0.168s, Critical Path: 0.00s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
//fortune:fortune_test PASSED in 0.3s
Executed 0 out of 1 test: 1 test passes.
```
You can use the `...` wildcard to run all tests. Bazel will also build targets
that aren't tests, so this can catch compile errors even in packages that don't
have tests.
```posix-shell theme={null}
$ bazel test //...
```
## Conclusion and further reading
In this tutorial, we built and tested a small Go project with Bazel, and we
learned some core Bazel concepts along the way.
* To get started building other applications with Bazel, see the tutorials for
[C++](/start/cpp), [Java](/start/java), [Android](/start/android-app), and
[iOS](/start/ios-app).
* You can also check the list of [recommended rules](/rules) for other
languages.
* For more information on Go, see the
[rules\_go](https://github.com/bazel-contrib/rules_go) module, especially the
[Core Go rules](https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/rules.md)
documentation.
* To learn more about working with Bazel modules outside your project, see
[external dependencies](/docs/external). In particular, for information on
how to depend on Go modules and toolchains through Bazel's module system,
see [Go with bzlmod](https://github.com/bazel-contrib/rules_go/tree/master/docs/go/core/bzlmod.md).
# Bazel Tutorial: Build an iOS App
Source: https://bazel.build/start/ios-app
This tutorial has been moved into the [bazelbuild/rules\_apple](https://github.com/bazelbuild/rules_apple/blob/master/doc/tutorials/ios-app.md) repository.
# Bazel Tutorial: Build a Java Project
Source: https://bazel.build/start/java
This tutorial covers the basics of building Java applications with
Bazel. You will set up your workspace and build a simple Java project that
illustrates key Bazel concepts, such as targets and `BUILD` files.
Estimated completion time: 30 minutes.
## What you'll learn
In this tutorial you learn how to:
* Build a target
* Visualize the project's dependencies
* Split the project into multiple targets and packages
* Control target visibility across packages
* Reference targets through labels
* Deploy a target
## Before you begin
### Install Bazel
To prepare for the tutorial, first [Install Bazel](/install) if
you don't have it installed already.
### Install the JDK
1. Install Java JDK (preferred version is 11, however versions between 8 and 15 are supported).
2. Set the JAVA\_HOME environment variable to point to the JDK.
* On Linux/macOS:
export JAVA\_HOME="$(dirname $(dirname $(realpath $(which javac))))"
* On Windows:
1. Open Control Panel.
2. Go to "System and Security" > "System" > "Advanced System Settings" > "Advanced" tab > "Environment Variables..." .
3. Under the "User variables" list (the one on the top), click "New\...".
4. In the "Variable name" field, enter `JAVA_HOME`.
5. Click "Browse Directory...".
6. Navigate to the JDK directory (for example `C:\Program Files\Java\jdk1.8.0_152`).
7. Click "OK" on all dialog windows.
### Get the sample project
Retrieve the sample project from Bazel's GitHub repository:
```posix-terminal theme={null}
git clone https://github.com/bazelbuild/examples
```
The sample project for this tutorial is in the `examples/java-tutorial`
directory and is structured as follows:
```
java-tutorial
├── BUILD
├── src
│ └── main
│ └── java
│ └── com
│ └── example
│ ├── cmdline
│ │ ├── BUILD
│ │ └── Runner.java
│ ├── Greeting.java
│ └── ProjectRunner.java
└── MODULE.bazel
```
## Build with Bazel
### Set up the workspace
Before you can build a project, you need to set up its workspace. A workspace is
a directory that holds your project's source files and Bazel's build outputs. It
also contains files that Bazel recognizes as special:
* The `MODULE.bazel` file, which identifies the directory and its contents as a
Bazel workspace and lives at the root of the project's directory structure,
* One or more `BUILD` files, which tell Bazel how to build different parts of
the project. (A directory within the workspace that contains a `BUILD` file
is a *package*. You will learn about packages later in this tutorial.)
To designate a directory as a Bazel workspace, create an empty file named
`MODULE.bazel` in that directory.
When Bazel builds the project, all inputs and dependencies must be in the same
workspace. Files residing in different workspaces are independent of one
another unless linked, which is beyond the scope of this tutorial.
### Understand the BUILD file
A `BUILD` file contains several different types of instructions for Bazel.
The most important type is the *build rule*, which tells Bazel how to build the
desired outputs, such as executable binaries or libraries. Each instance
of a build rule in the `BUILD` file is called a *target* and points to a
specific set of source files and dependencies. A target can also point to other
targets.
Take a look at the `java-tutorial/BUILD` file:
```python theme={null}
java_binary(
name = "ProjectRunner",
srcs = glob(["src/main/java/com/example/*.java"]),
)
```
In our example, the `ProjectRunner` target instantiates Bazel's built-in
[`java_binary` rule](/reference/be/java#java_binary). The rule tells Bazel to
build a `.jar` file and a wrapper shell script (both named after the target).
The attributes in the target explicitly state its dependencies and options.
While the `name` attribute is mandatory, many are optional. For example, in the
`ProjectRunner` rule target, `name` is the name of the target, `srcs` specifies
the source files that Bazel uses to build the target, and `main_class` specifies
the class that contains the main method. (You may have noticed that our example
uses [glob](/reference/be/functions#glob) to pass a set of source files to Bazel
instead of listing them one by one.)
### Build the project
To build your sample project, navigate to the `java-tutorial` directory
and run:
```posix-terminal theme={null}
bazel build //:ProjectRunner
```
In the target label, the `//` part is the location of the `BUILD` file
relative to the root of the workspace (in this case, the root itself),
and `ProjectRunner` is the target name in the `BUILD` file. (You will
learn about target labels in more detail at the end of this tutorial.)
Bazel produces output similar to the following:
```bash theme={null}
INFO: Found 1 target...
Target //:ProjectRunner up-to-date:
bazel-bin/ProjectRunner.jar
bazel-bin/ProjectRunner
INFO: Elapsed time: 1.021s, Critical Path: 0.83s
```
Congratulations, you just built your first Bazel target! Bazel places build
outputs in the `bazel-bin` directory at the root of the workspace. Browse
through its contents to get an idea for Bazel's output structure.
Now test your freshly built binary:
```posix-terminal theme={null}
bazel-bin/ProjectRunner
```
### Review the dependency graph
Bazel requires build dependencies to be explicitly declared in BUILD files.
Bazel uses those statements to create the project's dependency graph, which
enables accurate incremental builds.
To visualize the sample project's dependencies, you can generate a text
representation of the dependency graph by running this command at the
workspace root:
```posix-terminal theme={null}
bazel query --notool_deps --noimplicit_deps "deps(//:ProjectRunner)" --output graph
```
The above command tells Bazel to look for all dependencies for the target
`//:ProjectRunner` (excluding host and implicit dependencies) and format the
output as a graph.
Then, paste the text into [GraphViz](http://www.webgraphviz.com/).
As you can see, the project has a single target that build two source files with
no additional dependencies:
After you set up your workspace, build your project, and examine its
dependencies, then you can add some complexity.
## Refine your Bazel build
While a single target is sufficient for small projects, you may want to split
larger projects into multiple targets and packages to allow for fast incremental
builds (that is, only rebuild what's changed) and to speed up your builds by
building multiple parts of a project at once.
### Specify multiple build targets
You can split the sample project build into two targets. Replace the contents of
the `java-tutorial/BUILD` file with the following:
```python theme={null}
java_binary(
name = "ProjectRunner",
srcs = ["src/main/java/com/example/ProjectRunner.java"],
main_class = "com.example.ProjectRunner",
deps = [":greeter"],
)
java_library(
name = "greeter",
srcs = ["src/main/java/com/example/Greeting.java"],
)
```
With this configuration, Bazel first builds the `greeter` library, then the
`ProjectRunner` binary. The `deps` attribute in `java_binary` tells Bazel that
the `greeter` library is required to build the `ProjectRunner` binary.
To build this new version of the project, run the following command:
```posix-terminal theme={null}
bazel build //:ProjectRunner
```
Bazel produces output similar to the following:
```
INFO: Found 1 target...
Target //:ProjectRunner up-to-date:
bazel-bin/ProjectRunner.jar
bazel-bin/ProjectRunner
INFO: Elapsed time: 2.454s, Critical Path: 1.58s
```
Now test your freshly built binary:
```posix-terminal theme={null}
bazel-bin/ProjectRunner
```
If you now modify `ProjectRunner.java` and rebuild the project, Bazel only
recompiles that file.
Looking at the dependency graph, you can see that `ProjectRunner` depends on the
same inputs as it did before, but the structure of the build is different:
You've now built the project with two targets. The `ProjectRunner` target builds
one source files and depends on one other target (`:greeter`), which builds
one additional source file.
### Use multiple packages
Let’s now split the project into multiple packages. If you take a look at the
`src/main/java/com/example/cmdline` directory, you can see that it also contains
a `BUILD` file, plus some source files. Therefore, to Bazel, the workspace now
contains two packages, `//src/main/java/com/example/cmdline` and `//` (since
there is a `BUILD` file at the root of the workspace).
Take a look at the `src/main/java/com/example/cmdline/BUILD` file:
```python theme={null}
java_binary(
name = "runner",
srcs = ["Runner.java"],
main_class = "com.example.cmdline.Runner",
deps = ["//:greeter"],
)
```
The `runner` target depends on the `greeter` target in the `//` package (hence
the target label `//:greeter`) - Bazel knows this through the `deps` attribute.
Take a look at the dependency graph:
However, for the build to succeed, you must explicitly give the `runner` target
in `//src/main/java/com/example/cmdline/BUILD` visibility to targets in
`//BUILD` using the `visibility` attribute. This is because by default targets
are only visible to other targets in the same `BUILD` file. (Bazel uses target
visibility to prevent issues such as libraries containing implementation details
leaking into public APIs.)
To do this, add the `visibility` attribute to the `greeter` target in
`java-tutorial/BUILD` as shown below:
```python theme={null}
java_library(
name = "greeter",
srcs = ["src/main/java/com/example/Greeting.java"],
visibility = ["//src/main/java/com/example/cmdline:__pkg__"],
)
```
Now you can build the new package by running the following command at the root
of the workspace:
```posix-terminal theme={null}
bazel build //src/main/java/com/example/cmdline:runner
```
Bazel produces output similar to the following:
```
INFO: Found 1 target...
Target //src/main/java/com/example/cmdline:runner up-to-date:
bazel-bin/src/main/java/com/example/cmdline/runner.jar
bazel-bin/src/main/java/com/example/cmdline/runner
INFO: Elapsed time: 1.576s, Critical Path: 0.81s
```
Now test your freshly built binary:
```posix-terminal theme={null}
./bazel-bin/src/main/java/com/example/cmdline/runner
```
You've now modified the project to build as two packages, each containing one
target, and understand the dependencies between them.
## Use labels to reference targets
In `BUILD` files and at the command line, Bazel uses target labels to reference
targets - for example, `//:ProjectRunner` or
`//src/main/java/com/example/cmdline:runner`. Their syntax is as follows:
```
//path/to/package:target-name
```
If the target is a rule target, then `path/to/package` is the path to the
directory containing the `BUILD` file, and `target-name` is what you named the
target in the `BUILD` file (the `name` attribute). If the target is a file
target, then `path/to/package` is the path to the root of the package, and
`target-name` is the name of the target file, including its full path.
When referencing targets at the repository root, the package path is empty,
just use `//:target-name`. When referencing targets within the same `BUILD`
file, you can even skip the `//` workspace root identifier and just use
`:target-name`.
For example, for targets in the `java-tutorial/BUILD` file, you did not have to
specify a package path, since the workspace root is itself a package (`//`), and
your two target labels were simply `//:ProjectRunner` and `//:greeter`.
However, for targets in the `//src/main/java/com/example/cmdline/BUILD` file you
had to specify the full package path of `//src/main/java/com/example/cmdline`
and your target label was `//src/main/java/com/example/cmdline:runner`.
## Package a Java target for deployment
Let’s now package a Java target for deployment by building the binary with all
of its runtime dependencies. This lets you run the binary outside of your
development environment.
As you remember, the [java\_binary](/reference/be/java#java_binary) build rule
produces a `.jar` and a wrapper shell script. Take a look at the contents of
`runner.jar` using this command:
```posix-terminal theme={null}
jar tf bazel-bin/src/main/java/com/example/cmdline/runner.jar
```
The contents are:
```
META-INF/
META-INF/MANIFEST.MF
com/
com/example/
com/example/cmdline/
com/example/cmdline/Runner.class
```
As you can see, `runner.jar` contains `Runner.class`, but not its dependency,
`Greeting.class`. The `runner` script that Bazel generates adds `greeter.jar`
to the classpath, so if you leave it like this, it will run locally, but it
won't run standalone on another machine. Fortunately, the `java_binary` rule
allows you to build a self-contained, deployable binary. To build it, append
`_deploy.jar` to the target name:
```posix-terminal theme={null}
bazel build //src/main/java/com/example/cmdline:runner_deploy.jar
```
Bazel produces output similar to the following:
```
INFO: Found 1 target...
Target //src/main/java/com/example/cmdline:runner_deploy.jar up-to-date:
bazel-bin/src/main/java/com/example/cmdline/runner_deploy.jar
INFO: Elapsed time: 1.700s, Critical Path: 0.23s
```
You have just built `runner_deploy.jar`, which you can run standalone away from
your development environment since it contains the required runtime
dependencies. Take a look at the contents of this standalone JAR using the
same command as before:
```posix-terminal theme={null}
jar tf bazel-bin/src/main/java/com/example/cmdline/runner_deploy.jar
```
The contents include all of the necessary classes to run:
```
META-INF/
META-INF/MANIFEST.MF
build-data.properties
com/
com/example/
com/example/cmdline/
com/example/cmdline/Runner.class
com/example/Greeting.class
```
## Further reading
For more details, see:
* [rules\_jvm\_external](https://github.com/bazelbuild/rules_jvm_external) for
rules to manage transitive Maven dependencies.
* [External Dependencies](/docs/external) to learn more about working with
local and remote repositories.
* The [other rules](/rules) to learn more about Bazel.
* The [C++ build tutorial](/start/cpp) to get started with building
C++ projects with Bazel.
* The [Android application tutorial](/start/android-app) and
[iOS application tutorial](/start/ios-app)) to get started with
building mobile applications for Android and iOS with Bazel.
Happy building!
# Bazel Tutorial: Configure C++ Toolchains
Source: https://bazel.build/tutorials/ccp-toolchain-config
This tutorial uses an example scenario to describe how to configure C++
toolchains for a project.
## What you'll learn
In this tutorial you learn how to:
* Set up the build environment
* Use `--toolchain_resolution_debug` to debug toolchain resolution
* Configure the C++ toolchain
* Create a Starlark rule that provides additional configuration for the
`cc_toolchain` so that Bazel can build the application with `clang`
* Build the C++ binary by running `bazel build //main:hello-world` on a
Linux machine
* Cross-compile the binary for android by running `bazel build
//main:hello-world --platforms=//:android_x86_64`
## Before you begin
This tutorial assumes you are on Linux and have successfully built C++
applications and installed the appropriate tooling and libraries. The tutorial
uses `clang version 19`, which you can install on your system.
### Set up the build environment
Set up your build environment as follows:
1. If you have not already done so, [download and install Bazel 7.0.2](https://bazel.build/install) or later.
2. Add an empty `MODULE.bazel` file at the root folder.
3. Add the following `cc_binary` target to the `main/BUILD` file:
```python theme={null}
cc_binary(
name = "hello-world",
srcs = ["hello-world.cc"],
)
```
Because Bazel uses many internal tools written in C++ during the build, such
as `process-wrapper`, the pre-existing default C++ toolchain is specified
for the host platform. This enables these internal tools to build using that
toolchain of the one created in this tutorial. Hence, the `cc_binary` target
is also built with the default toolchain.
4. Run the build with the following command:
```bash theme={null}
bazel build //main:hello-world
```
The build succeeds without any toolchain registered in `MODULE.bazel`.
To further see what's under the hood, run:
```bash theme={null}
bazel build //main:hello-world --toolchain_resolution_debug='@bazel_tools//tools/cpp:toolchain_type'
INFO: ToolchainResolution: Target platform @@platforms//host:host: Selected execution platform @@platforms//host:host, type @@bazel_tools//tools/cpp:toolchain_type -> toolchain @@bazel_tools+cc_configure_extension+local_config_cc//:cc-compiler-k8
```
Without specifying `--platforms`, Bazel builds the target for
`@platforms//host` using
`@bazel_tools+cc_configure_extension+local_config_cc//:cc-compiler-k8`.
## Configure the C++ toolchain
To configure the C++ toolchain, repeatedly build the application and eliminate
each error one by one as described as following.
Note: This tutorial assumes you're using Bazel 7.0.2 or later. If you're using
an older release of Bazel, use `--incompatible_enable_cc_toolchain_resolution`
flag to enable C++ toolchain resolution.
It also assumes `clang version 9.0.1`, although the details should only change
slightly between different versions of clang.
1. Add `toolchain/BUILD` with
```python theme={null}
filegroup(name = "empty")
cc_toolchain(
name = "linux_x86_64_toolchain",
toolchain_identifier = "linux_x86_64-toolchain",
toolchain_config = ":linux_x86_64_toolchain_config",
all_files = ":empty",
compiler_files = ":empty",
dwp_files = ":empty",
linker_files = ":empty",
objcopy_files = ":empty",
strip_files = ":empty",
supports_param_files = 0,
)
toolchain(
name = "cc_toolchain_for_linux_x86_64",
toolchain = ":linux_x86_64_toolchain",
toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
exec_compatible_with = [
"@platforms//cpu:x86_64",
"@platforms//os:linux",
],
target_compatible_with = [
"@platforms//cpu:x86_64",
"@platforms//os:linux",
],
)
```
Then add appropriate dependencies and register the toolchain with
`MODULE.bazel` with
```python theme={null}
bazel_dep(name = "platforms", version = "0.0.10")
register_toolchains(
"//toolchain:cc_toolchain_for_linux_x86_64"
)
```
This step defines a `cc_toolchain` and binds it to a `toolchain` target for
the host configuration.
2. Run the build again. Because the `toolchain` package doesn't yet define the
`linux_x86_64_toolchain_config` target, Bazel throws the following error:
```bash theme={null}
ERROR: toolchain/BUILD:4:13: in toolchain_config attribute of cc_toolchain rule //toolchain:linux_x86_64_toolchain: rule '//toolchain:linux_x86_64_toolchain_config' does not exist.
```
3. In the `toolchain/BUILD` file, define an empty filegroup as follows:
```python theme={null}
package(default_visibility = ["//visibility:public"])
filegroup(name = "linux_x86_64_toolchain_config")
```
4. Run the build again. Bazel throws the following error:
```bash theme={null}
'//toolchain:linux_x86_64_toolchain_config' does not have mandatory providers: 'CcToolchainConfigInfo'.
```
`CcToolchainConfigInfo` is a provider that you use to configure your C++
toolchains. To fix this error, create a Starlark rule that provides
`CcToolchainConfigInfo` to Bazel by making a
`toolchain/cc_toolchain_config.bzl` file with the following content:
```python theme={null}
def _impl(ctx):
return cc_common.create_cc_toolchain_config_info(
ctx = ctx,
toolchain_identifier = "k8-toolchain",
host_system_name = "local",
target_system_name = "local",
target_cpu = "k8",
target_libc = "unknown",
compiler = "clang",
abi_version = "unknown",
abi_libc_version = "unknown",
)
cc_toolchain_config = rule(
implementation = _impl,
attrs = {},
provides = [CcToolchainConfigInfo],
)
```
`cc_common.create_cc_toolchain_config_info()` creates the needed provider
`CcToolchainConfigInfo`. To use the `cc_toolchain_config` rule, add a load
statement to `toolchain/BUILD` right below the package statement:
```python theme={null}
load(":cc_toolchain_config.bzl", "cc_toolchain_config")
```
And replace the "linux\_x86\_64\_toolchain\_config" filegroup with a declaration
of a `cc_toolchain_config` rule:
```python theme={null}
cc_toolchain_config(name = "linux_x86_64_toolchain_config")
```
5. Run the build again. Bazel throws the following error:
```bash theme={null}
.../BUILD:1:1: C++ compilation of rule '//:hello-world' failed (Exit 1)
src/main/tools/linux-sandbox-pid1.cc:421:
"execvp(toolchain/DUMMY_GCC_TOOL, 0x11f20e0)": No such file or directory
Target //:hello-world failed to build`
```
At this point, Bazel has enough information to attempt building the code but
it still does not know what tools to use to complete the required build
actions. You will modify the Starlark rule implementation to tell Bazel what
tools to use. For that, you need the `tool_path()` constructor from
[`@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl`](https://source.bazel.build/bazel/+/4eea5c62a566d21832c93e4c18ec559e75d5c1ce:tools/cpp/cc_toolchain_config_lib.bzl;l=400):
```python theme={null}
# toolchain/cc_toolchain_config.bzl:
# NEW
load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path")
def _impl(ctx):
tool_paths = [ # NEW
tool_path(
name = "gcc", # Compiler is referenced by the name "gcc" for historic reasons.
path = "/usr/bin/clang",
),
tool_path(
name = "ld",
path = "/usr/bin/ld",
),
tool_path(
name = "ar",
path = "/usr/bin/ar",
),
tool_path(
name = "cpp",
path = "/bin/false",
),
tool_path(
name = "gcov",
path = "/bin/false",
),
tool_path(
name = "nm",
path = "/bin/false",
),
tool_path(
name = "objdump",
path = "/bin/false",
),
tool_path(
name = "strip",
path = "/bin/false",
),
]
return cc_common.create_cc_toolchain_config_info(
ctx = ctx,
toolchain_identifier = "local",
host_system_name = "local",
target_system_name = "local",
target_cpu = "k8",
target_libc = "unknown",
compiler = "clang",
abi_version = "unknown",
abi_libc_version = "unknown",
tool_paths = tool_paths, # NEW
)
```
Make sure that `/usr/bin/clang` and `/usr/bin/ld` are the correct paths for
your system. Note that the compiler is referenced by the name "gcc" for
historic reasons.
6. Run the build again. Bazel throws the following error:
```bash theme={null}
ERROR: main/BUILD:3:10: Compiling main/hello-world.cc failed: absolute path inclusion(s) found in rule '//main:hello-world':
the source file 'main/hello-world.cc' includes the following non-builtin files with absolute paths (if these are builtin files, make sure these paths are in your toolchain):
'/usr/include/c++/13/ctime'
'/usr/include/x86_64-linux-gnu/c++/13/bits/c++config.h'
'/usr/include/x86_64-linux-gnu/c++/13/bits/os_defines.h'
...
```
Bazel needs to know where to search for included headers. There are multiple
ways to solve this, such as using the `includes` attribute of `cc_binary`,
but here this is solved at the toolchain level with the
[`cxx_builtin_include_directories`](/rules/lib/toplevel/cc_common#create_cc_toolchain_config_info)
parameter of `cc_common.create_cc_toolchain_config_info`. Beware that if you
are using a different version of `clang`, the include path will be
different. These paths may also be different depending on the distribution.
Modify the return value in `toolchain/cc_toolchain_config.bzl` to look like
this:
```python theme={null}
return cc_common.create_cc_toolchain_config_info(
ctx = ctx,
cxx_builtin_include_directories = [ # NEW
"/usr/lib/llvm-19/lib/clang/19/include",
"/usr/include",
],
toolchain_identifier = "local",
host_system_name = "local",
target_system_name = "local",
target_cpu = "k8",
target_libc = "unknown",
compiler = "clang",
abi_version = "unknown",
abi_libc_version = "unknown",
tool_paths = tool_paths,
)
```
7. Run the build command again, you will see an error like:
```bash theme={null}
/usr/bin/ld: bazel-out/k8-fastbuild/bin/main/_objs/hello-world/hello-world.o: in function `print_localtime()':
hello-world.cc:(.text+0x68): undefined reference to `std::cout'
```
The reason for this is because the linker is missing the C++ standard
library and it can't find its symbols. There are many ways to solve this,
such as using the `linkopts` attribute of `cc_binary`. Here it is solved by
making sure that any target using the toolchain doesn't have to specify this
flag.
Copy the following code to `toolchain/cc_toolchain_config.bzl`:
```python theme={null}
# NEW
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
# NEW
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"feature", # NEW
"flag_group", # NEW
"flag_set", # NEW
"tool_path",
)
all_link_actions = [ # NEW
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_nodeps_dynamic_library,
]
def _impl(ctx):
tool_paths = [
tool_path(
name = "gcc", # Compiler is referenced by the name "gcc" for historic reasons.
path = "/usr/bin/clang",
),
tool_path(
name = "ld",
path = "/usr/bin/ld",
),
tool_path(
name = "ar",
path = "/bin/false",
),
tool_path(
name = "cpp",
path = "/bin/false",
),
tool_path(
name = "gcov",
path = "/bin/false",
),
tool_path(
name = "nm",
path = "/bin/false",
),
tool_path(
name = "objdump",
path = "/bin/false",
),
tool_path(
name = "strip",
path = "/bin/false",
),
]
features = [ # NEW
feature(
name = "default_linker_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_link_actions,
flag_groups = ([
flag_group(
flags = [
"-lstdc++",
],
),
]),
),
],
),
]
return cc_common.create_cc_toolchain_config_info(
ctx = ctx,
features = features, # NEW
cxx_builtin_include_directories = [
"/usr/lib/llvm-19/lib/clang/19/include",
"/usr/include",
],
toolchain_identifier = "local",
host_system_name = "local",
target_system_name = "local",
target_cpu = "k8",
target_libc = "unknown",
compiler = "clang",
abi_version = "unknown",
abi_libc_version = "unknown",
tool_paths = tool_paths,
)
cc_toolchain_config = rule(
implementation = _impl,
attrs = {},
provides = [CcToolchainConfigInfo],
)
```
Note that this code uses the GNU C++ library libstdc++. If you want to use
the LLVM C++ library, use "-lc++" instead of "-lstdc++".
8. Running `bazel build //main:hello-world`, it should finally build the binary
successfully for host.
9. In `toolchain/BUILD`, copy the `cc_toolchain_config`, `cc_toolchain`, and
`toolchain` targets and replace `linux_x86_64` with `android_x86_64`in
target names.
In `MODULE.bazel`, register the toolchain for android
```python theme={null}
register_toolchains(
"//toolchain:cc_toolchain_for_linux_x86_64",
"//toolchain:cc_toolchain_for_android_x86_64"
)
```
10. Run `bazel build //main:hello-world --android_platforms=//toolchain:android_x86_64` to build the binary for
Android.
In practice, Linux and Android should have different C++ toolchain configs. You
can either modify the existing `cc_toolchain_config` for the differences or
create a separate rules (i.e. `CcToolchainConfigInfo` provider) for separate
platforms.
## Review your work
In this tutorial you learned how to configure a basic C++ toolchain, but
toolchains are more powerful than this example.
The key takeaways are:
* You need to specify a matching `platforms` flag in the command line for
Bazel to resolve to the toolchain for the same constraint values on the
platform. The documentation holds more [information about language specific configuration flags](/concepts/platforms).
* You have to let the toolchain know where the tools live. In this tutorial
there is a simplified version where you access the tools from the system. If
you are interested in a more self-contained approach, you can read about
[external dependencies](/external/overview). Your tools could come from a
different module and you would have to make their files available to the
`cc_toolchain` with target dependencies on attributes, such as
`compiler_files`. The `tool_paths` would need to be changed as well.
* You can create features to customize which flags should be passed to
different actions, be it linking or any other type of action.
## Further reading
For more details, see [C++ toolchain configuration](/docs/cc-toolchain-config-reference)
# Review the dependency graph
Source: https://bazel.build/tutorials/cpp-dependency
A successful build has all of its dependencies explicitly stated in the `BUILD`
file. Bazel uses those statements to create the project's dependency graph,
which enables accurate incremental builds.
To visualize the sample project's dependencies, you can generate a text
representation of the dependency graph by running this command at the
workspace root:
```
bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" \
--output graph
```
The above command tells Bazel to look for all dependencies for the target
`//main:hello-world` (excluding host and implicit dependencies) and format the
output as a graph.
Then, paste the text into [GraphViz](http://www.webgraphviz.com/).
On Ubuntu, you can view the graph locally by installing GraphViz and the xdot
Dot Viewer:
```
sudo apt update && sudo apt install graphviz xdot
```
Then you can generate and view the graph by piping the text output above
straight to xdot:
```
xdot <(bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" \
--output graph)
```
As you can see, the first stage of the sample project has a single target
that builds a single source file with no additional dependencies:
**Figure 1.** Dependency graph for `hello-world` displays a single target with a single
source file.
After you set up your workspace, build your project, and examine its
dependencies, then you can add some complexity.
# Use labels to reference targets
Source: https://bazel.build/tutorials/cpp-labels
In `BUILD` files and at the command line, Bazel uses *labels* to reference
targets - for example, `//main:hello-world` or `//lib:hello-time`. Their syntax
is:
```
//path/to/package:target-name
```
If the target is a rule target, then `path/to/package` is the path from the
workspace root (the directory containing the `MODULE.bazel` file) to the directory
containing the `BUILD` file, and `target-name` is what you named the target
in the `BUILD` file (the `name` attribute). If the target is a file target,
then `path/to/package` is the path to the root of the package, and
`target-name` is the name of the target file, including its full
path relative to the root of the package (the directory containing the
package's `BUILD` file).
When referencing targets at the repository root, the package path is empty,
just use `//:target-name`. When referencing targets within the same `BUILD`
file, you can even skip the `//` workspace root identifier and just use
`:target-name`.
# Common C++ Build Use Cases
Source: https://bazel.build/tutorials/cpp-use-cases
Here you will find some of the most common use cases for building C++ projects
with Bazel. If you have not done so already, get started with building C++
projects with Bazel by completing the tutorial
[Introduction to Bazel: Build a C++ Project](/start/cpp).
For information on cc\_library and hdrs header files, see
cc\_library.
## Including multiple files in a target
You can include multiple files in a single target with
glob.
For example:
```python theme={null}
cc_library(
name = "build-all-the-files",
srcs = glob(["*.cc"]),
hdrs = glob(["*.h"]),
)
```
With this target, Bazel will build all the `.cc` and `.h` files it finds in the
same directory as the `BUILD` file that contains this target (excluding
subdirectories).
## Using transitive includes
If a file includes a header, then any rule with that file as a source (that is,
having that file in the `srcs`, `hdrs`, or `textual_hdrs` attribute) should
depend on the included header's library rule. Conversely, only direct
dependencies need to be specified as dependencies. For example, suppose
`sandwich.h` includes `bread.h` and `bread.h` includes `flour.h`. `sandwich.h`
doesn't include `flour.h` (who wants flour in their sandwich?), so the `BUILD`
file would look like this:
```python theme={null}
cc_library(
name = "sandwich",
srcs = ["sandwich.cc"],
hdrs = ["sandwich.h"],
deps = [":bread"],
)
cc_library(
name = "bread",
srcs = ["bread.cc"],
hdrs = ["bread.h"],
deps = [":flour"],
)
cc_library(
name = "flour",
srcs = ["flour.cc"],
hdrs = ["flour.h"],
)
```
Here, the `sandwich` library depends on the `bread` library, which depends
on the `flour` library.
## Adding include paths
Sometimes you cannot (or do not want to) root include paths at the workspace
root. Existing libraries might already have an include directory that doesn't
match its path in your workspace. For example, suppose you have the following
directory structure:
```
└── my-project
├── legacy
│ └── some_lib
│ ├── BUILD
│ ├── include
│ │ └── some_lib.h
│ └── some_lib.cc
└── MODULE.bazel
```
Bazel will expect `some_lib.h` to be included as
`legacy/some_lib/include/some_lib.h`, but suppose `some_lib.cc` includes
`"some_lib.h"`. To make that include path valid,
`legacy/some_lib/BUILD` will need to specify that the `some_lib/include`
directory is an include directory:
```python theme={null}
cc_library(
name = "some_lib",
srcs = ["some_lib.cc"],
hdrs = ["include/some_lib.h"],
local_includes = ["include"],
)
```
Paths in `local_includes` are relative to the package. To also make the
include path available to targets that depend on `some_lib`, use the
`includes` attribute instead.
## Include external libraries
Suppose you are using [Google Test](https://github.com/google/googletest)
.
You can add a dependency on it in the `MODULE.bazel` file to
download Google Test and make it available in your repository:
```python theme={null}
bazel_dep(name = "googletest", version = "1.15.2")
```
## Writing and running C++ tests
For example, you could create a test `./test/hello-test.cc`, such as:
```cpp theme={null}
#include "gtest/gtest.h"
#include "main/hello-greet.h"
TEST(HelloTest, GetGreet) {
EXPECT_EQ(get_greet("Bazel"), "Hello Bazel");
}
```
Then create `./test/BUILD` file for your tests:
```python theme={null}
cc_test(
name = "hello-test",
srcs = ["hello-test.cc"],
deps = [
"@googletest//:gtest_main",
"//main:hello-greet",
],
)
```
To make `hello-greet` visible to `hello-test`, you must add
`"//test:__pkg__",` to the `visibility` attribute in `./main/BUILD`.
Now you can use `bazel test` to run the test.
```
bazel test test:hello-test
```
This produces the following output:
```
INFO: Found 1 test target...
Target //test:hello-test up-to-date:
bazel-bin/test/hello-test
INFO: Elapsed time: 4.497s, Critical Path: 2.53s
//test:hello-test PASSED in 0.3s
Executed 1 out of 1 tests: 1 test passes.
```
## Adding dependencies on precompiled libraries
If you want to use a library of which you only have a compiled version (for
example, headers and a `.so` file) wrap it in a `cc_library` rule:
```python theme={null}
cc_library(
name = "mylib",
srcs = ["mylib.so"],
hdrs = ["mylib.h"],
)
```
This way, other C++ targets in your workspace can depend on this rule.
# Platforms
Source: https://bazel.build/concepts/platforms
## Intro
Bazel can build and test code on a variety of hardware, operating systems, and
system configurations. This can involve different versions of build tools like
linkers and compilers. To help manage this complexity, Bazel has the concepts
of *constraints* and *platforms*.
A *constraint* is a distinguishing property of a build or production machine.
Common constraints are CPU architecture, presence or absence of a GPU, or
version of a locally installed compiler. But constraints can be *anything* that
meaningfully distinguishes machines when orchestrating build work.
A *platform* is a collection of constraints that specifies a complete machine.
Bazel uses this concept to let developers choose which machines they want to
build for, which machines should run compile and test actions, and which
[toolchains](/extending/toolchains) build actions should compile with.
Developers can also use constraints to [select](/docs/configurable-attributes)
custom properties or dependencies on their build rules. For example: "*use
`src_arm.cc` when the build targets an Arm machine*".
## Platform types
Bazel recognizes three roles a platform may play:
* **Host** - The platform on which Bazel itself runs.
* **Execution** - A platform which runs compile actions to produce build outputs.
* **Target** - A platform the code being built should run on.
Note: Builds only have one host platform, but often have multiple execution and
target platforms. For example, both remote Linux CI machines and developer Macs
may run build actions. And mobile apps have code for multiple phone types and
hardware extensions.
Builds generally have three kinds of relationships to platforms:
* **Single-platform builds** - Host, execution, and target platforms are the
same. For example, building on a developer machine without remote execution,
then running the built binary on the same machine.
* **Cross-compilation builds** - Host and execution platforms are the same,
but the target platform is different. For example, building an iOS app on a
Macbook Pro without remote execution.
* **Multi-platform builds** - Host, execution, and target platforms are all
different. For example, building an iOS app on a Macbook Pro and using remote
Linux machines to compile C++ actions that don't need Xcode.
## Specifying platforms
The most common way for developers to use platforms is to specify desired
target machines with the `--platforms` flag:
```shell theme={null}
$ bazel build //:my_linux_app --platforms=//myplatforms:linux_x86
```
Organizations generally maintain their own platform definitions because build
machine setups vary between organizations.
When `--platforms` isn't set, it defaults to `@platforms//host`. This is
specially defined to auto-detect the host machine's OS and CPU properties so
builds target the same machine Bazel runs on. Build rules can
[select](/docs/configurable-attributes) on these properties with the
[@platforms/os](https://github.com/bazelbuild/platforms/blob/main/os/BUILD) and
[@platforms/cpu](https://github.com/bazelbuild/platforms/blob/main/cpu/BUILD)
constraints.
## Generally useful constraints and platforms
To keep the ecosystem consistent, Bazel team maintains a repository with
constraint definitions for the most popular CPU architectures and operating
systems. These are all defined in
[https://github.com/bazelbuild/platforms](https://github.com/bazelbuild/platforms).
Bazel ships with the following special platform definition:
`@platforms//host` (aliased as `@bazel_tools//tools:host_platform`). This
auto-detects the OS and CPU properties of the machine Bazel runs on.
## Defining constraints
Constraints are modeled with the [`constraint_setting`][constraint_setting] and
[`constraint_value`][constraint_value] build rules.
[constraint_setting]: /reference/be/platforms-and-toolchains#constraint_setting
[constraint_value]: /reference/be/platforms-and-toolchains#constraint_value
`constraint_setting` declares a type of property. For example:
```python theme={null}
constraint_setting(name = "cpu")
```
`constraint_value` declares a possible value for that property:
```python theme={null}
constraint_value(
name = "x86",
constraint_setting = ":cpu"
)
```
These can be referenced as labels when defining platforms or customizing build rules
on them. If the above examples are defined in `cpus/BUILD`, you can reference
the `x86` constraint as `//cpus:x86`.
If visibility allows, you can extend an existing `constraint_setting` by
defining your own value for it.
## Defining platforms
The [`platform`](/reference/be/platforms-and-toolchains#platform) build rule
defines a platform as a collection of `constraint_value`s:
```python theme={null}
platform(
name = "linux_x86",
constraint_values = [
"@platforms//os:linux",
"@platforms//cpu:x86",
],
)
```
This models a machine that must have both the `@platforms//os:linux` and `@platforms//cpu:x86`
constraints.
Platforms may only have one `constraint_value` for a given `constraint_setting`.
This means, for example, a platform can't have two CPUs unless you create another
`constraint_setting` type to model the second value.
## Skipping incompatible targets
When building for a specific target platform it is often desirable to skip
targets that will never work on that platform. For example, your Windows device
driver is likely going to generate lots of compiler errors when building on a
Linux machine with `//...`. Use the
[`target_compatible_with`](/reference/be/common-definitions#common.target_compatible_with)
attribute to tell Bazel what target platform constraints your code has.
The simplest use of this attribute restricts a target to a single platform.
The target won't be built for any platform that doesn't satisfy all of the
constraints. The following example restricts `win_driver_lib.cc` to 64-bit
Windows.
```python theme={null}
cc_library(
name = "win_driver_lib",
srcs = ["win_driver_lib.cc"],
target_compatible_with = [
"@platforms//cpu:x86_64",
"@platforms//os:windows",
],
)
```
`:win_driver_lib` is *only* compatible for building with 64-bit Windows and
incompatible with all else. Incompatibility is transitive. Any targets
that transitively depend on an incompatible target are themselves considered
incompatible.
### When are targets skipped?
Targets are skipped when they are considered incompatible and included in the
build as part of a target pattern expansion. For example, the following two
invocations skip any incompatible targets found in a target pattern expansion.
```console theme={null}
$ bazel build --platforms=//:myplatform //...
```
```console theme={null}
$ bazel build --platforms=//:myplatform //:all
```
Incompatible tests in a [`test_suite`](/reference/be/general#test_suite) are
similarly skipped if the `test_suite` is specified on the command line with
[`--expand_test_suites`](/reference/command-line-reference#flag--expand_test_suites).
In other words, `test_suite` targets on the command line behave like `:all` and
`...`. Using `--noexpand_test_suites` prevents expansion and causes
`test_suite` targets with incompatible tests to also be incompatible.
Explicitly specifying an incompatible target on the command line results in an
error message and a failed build.
```console theme={null}
$ bazel build --platforms=//:myplatform //:target_incompatible_with_myplatform
...
ERROR: Target //:target_incompatible_with_myplatform is incompatible and cannot be built, but was explicitly requested.
...
FAILED: Build did NOT complete successfully
```
Incompatible explicit targets are silently skipped if
`--skip_incompatible_explicit_targets` is enabled.
### More expressive constraints
For more flexibility in expressing constraints, use the
`@platforms//:incompatible`
[`constraint_value`](/reference/be/platforms-and-toolchains#constraint_value)
that no platform satisfies.
Use [`select()`](/reference/be/functions#select) in combination with
`@platforms//:incompatible` to express more complicated restrictions. For
example, use it to implement basic OR logic. The following marks a library
compatible with macOS and Linux, but no other platforms.
Note: An empty constraints list is equivalent to "compatible with everything".
```python theme={null}
cc_library(
name = "unixish_lib",
srcs = ["unixish_lib.cc"],
target_compatible_with = select({
"@platforms//os:osx": [],
"@platforms//os:linux": [],
"//conditions:default": ["@platforms//:incompatible"],
}),
)
```
The above can be interpreted as follows:
1. When targeting macOS, the target has no constraints.
2. When targeting Linux, the target has no constraints.
3. Otherwise, the target has the `@platforms//:incompatible` constraint. Because
`@platforms//:incompatible` is not part of any platform, the target is
deemed incompatible.
To make your constraints more readable, use
[skylib](https://github.com/bazelbuild/bazel-skylib)'s
[`selects.with_or()`](https://github.com/bazelbuild/bazel-skylib/blob/main/docs/selects_doc.md#selectswith_or).
You can express inverse compatibility in a similar way. The following example
describes a library that is compatible with everything *except* for ARM.
```python theme={null}
cc_library(
name = "non_arm_lib",
srcs = ["non_arm_lib.cc"],
target_compatible_with = select({
"@platforms//cpu:arm": ["@platforms//:incompatible"],
"//conditions:default": [],
}),
)
```
### Detecting incompatible targets using `bazel cquery`
You can use the
[`IncompatiblePlatformProvider`](/rules/lib/providers/IncompatiblePlatformProvider)
in `bazel cquery`'s [Starlark output format](/query/cquery#output-format-definition) to distinguish
incompatible targets from compatible ones.
This can be used to filter out incompatible targets. The example below will
only print the labels for targets that are compatible. Incompatible targets are
not printed.
```console theme={null}
$ cat example.cquery
def format(target):
if "IncompatiblePlatformProvider" not in providers(target):
return target.label
return ""
$ bazel cquery //... --output=starlark --starlark:file=example.cquery
```
### Known Issues
Incompatible targets [ignore visibility restrictions](https://github.com/bazelbuild/bazel/issues/16044).
# Aspects
Source: https://bazel.build/extending/aspects
This page explains the basics and benefits of using
[aspects](/rules/lib/globals/bzl#aspect) and provides simple and advanced
examples.
Aspects allow augmenting build dependency graphs with additional information
and actions. Some typical scenarios when aspects can be useful:
* IDEs that integrate Bazel can use aspects to collect information about the
project.
* Code generation tools can leverage aspects to execute on their inputs in
*target-agnostic* manner. As an example, `BUILD` files can specify a hierarchy
of [protobuf](https://developers.google.com/protocol-buffers/) library
definitions, and language-specific rules can use aspects to attach
actions generating protobuf support code for a particular language.
## Aspect basics
`BUILD` files provide a description of a project’s source code: what source
files are part of the project, what artifacts (*targets*) should be built from
those files, what the dependencies between those files are, etc. Bazel uses
this information to perform a build, that is, it figures out the set of actions
needed to produce the artifacts (such as running compiler or linker) and
executes those actions. Bazel accomplishes this by constructing a *dependency
graph* between targets and visiting this graph to collect those actions.
Consider the following `BUILD` file:
```python theme={null}
java_library(name = 'W', ...)
java_library(name = 'Y', deps = [':W'], ...)
java_library(name = 'Z', deps = [':W'], ...)
java_library(name = 'Q', ...)
java_library(name = 'T', deps = [':Q'], ...)
java_library(name = 'X', deps = [':Y',':Z'], runtime_deps = [':T'], ...)
```
This `BUILD` file defines a dependency graph shown in the following figure:
**Figure 1.** `BUILD` file dependency graph.
Bazel analyzes this dependency graph by calling an implementation function of
the corresponding [rule](/extending/rules) (in this case "java\_library") for every
target in the above example. Rule implementation functions generate actions that
build artifacts, such as `.jar` files, and pass information, such as locations
and names of those artifacts, to the reverse dependencies of those targets in
[providers](/extending/rules#providers).
Aspects are similar to rules in that they have an implementation function that
generates actions and returns providers. However, their power comes from
the way the dependency graph is built for them. An aspect has an implementation
and a list of all attributes it propagates along. Consider an aspect A that
propagates along attributes named "deps". This aspect can be applied to
a target X, yielding an aspect application node A(X). During its application,
aspect A is applied recursively to all targets that X refers to in its "deps"
attribute (all attributes in A's propagation list).
Thus a single act of applying aspect A to a target X yields a "shadow graph" of
the original dependency graph of targets shown in the following figure:
**Figure 2.** Build graph with aspects.
The only edges that are shadowed are the edges along the attributes in
the propagation set, thus the `runtime_deps` edge is not shadowed in this
example. An aspect implementation function is then invoked on all nodes in
the shadow graph similar to how rule implementations are invoked on the nodes
of the original graph.
## Simple example
This example demonstrates how to recursively print the source files for a
rule and all of its dependencies that have a `deps` attribute. It shows
an aspect implementation, an aspect definition, and how to invoke the aspect
from the Bazel command line.
```python theme={null}
def _print_aspect_impl(target, ctx):
# Make sure the rule has a srcs attribute.
if hasattr(ctx.rule.attr, 'srcs'):
# Iterate through the files that make up the sources and
# print their paths.
for src in ctx.rule.attr.srcs:
for f in src.files.to_list():
print(f.path)
return []
print_aspect = aspect(
implementation = _print_aspect_impl,
attr_aspects = ['deps'],
required_providers = [CcInfo],
)
```
Let's break the example up into its parts and examine each one individually.
### Aspect definition
```python theme={null}
print_aspect = aspect(
implementation = _print_aspect_impl,
attr_aspects = ['deps'],
required_providers = [CcInfo],
)
```
Aspect definitions are similar to rule definitions, and defined using
the [`aspect`](/rules/lib/globals/bzl#aspect) function.
Just like a rule, an aspect has an implementation function which in this case is
`_print_aspect_impl`.
`attr_aspects` is a list of rule attributes along which the aspect propagates.
In this case, the aspect will propagate along the `deps` attribute of the
rules that it is applied to.
Another common argument for `attr_aspects` is `['*']` which would propagate the
aspect to all attributes of a rule.
`required_providers` is a list of providers that allows the aspect to limit
its propagation to only the targets whose rules advertise its required
providers. For more details consult
[the documentation of the aspect function](/rules/lib/globals/bzl#aspect).
In this case, the aspect will only apply on targets that declare `CcInfo`
provider.
### Aspect implementation
```python theme={null}
def _print_aspect_impl(target, ctx):
# Make sure the rule has a srcs attribute.
if hasattr(ctx.rule.attr, 'srcs'):
# Iterate through the files that make up the sources and
# print their paths.
for src in ctx.rule.attr.srcs:
for f in src.files.to_list():
print(f.path)
return []
```
Aspect implementation functions are similar to the rule implementation
functions. They return [providers](/extending/rules#providers), can generate
[actions](/extending/rules#actions), and take two arguments:
* `target`: the [target](/rules/lib/builtins/Target) the aspect is being applied to.
* `ctx`: [`ctx`](/rules/lib/builtins/ctx) object that can be used to access attributes
and generate outputs and actions.
The implementation function can access the attributes of the target rule via
[`ctx.rule.attr`](/rules/lib/builtins/ctx#rule). It can examine providers that are
provided by the target to which it is applied (via the `target` argument).
Aspects are required to return a list of providers. In this example, the aspect
does not provide anything, so it returns an empty list.
### Invoking the aspect using the command line
The simplest way to apply an aspect is from the command line using the
[`--aspects`](/reference/command-line-reference#flag--aspects)
argument. Assuming the aspect above were defined in a file named `print.bzl`
this:
```bash theme={null}
bazel build //MyExample:example --aspects print.bzl%print_aspect
```
would apply the `print_aspect` to the target `example` and all of the
target rules that are accessible recursively via the `deps` attribute.
The `--aspects` flag takes one argument, which is a specification of the aspect
in the format `%`.
## Advanced example
The following example demonstrates using an aspect from a target rule
that counts files in targets, potentially filtering them by extension.
It shows how to use a provider to return values, how to use parameters to pass
an argument into an aspect implementation, and how to invoke an aspect from a rule.
Note: Aspects added in rules' attributes are called *rule-propagated aspects* as
opposed to *command-line aspects* that are specified using the `--aspects`
flag.
`file_count.bzl` file:
```python theme={null}
FileCountInfo = provider(
fields = {
'count' : 'number of files'
}
)
def _file_count_aspect_impl(target, ctx):
count = 0
# Make sure the rule has a srcs attribute.
if hasattr(ctx.rule.attr, 'srcs'):
# Iterate through the sources counting files
for src in ctx.rule.attr.srcs:
for f in src.files.to_list():
if ctx.attr.extension == '*' or ctx.attr.extension == f.extension:
count = count + 1
# Get the counts from our dependencies.
for dep in ctx.rule.attr.deps:
count = count + dep[FileCountInfo].count
return [FileCountInfo(count = count)]
file_count_aspect = aspect(
implementation = _file_count_aspect_impl,
attr_aspects = ['deps'],
attrs = {
'extension' : attr.string(values = ['*', 'h', 'cc']),
}
)
def _file_count_rule_impl(ctx):
for dep in ctx.attr.deps:
print(dep[FileCountInfo].count)
file_count_rule = rule(
implementation = _file_count_rule_impl,
attrs = {
'deps' : attr.label_list(aspects = [file_count_aspect]),
'extension' : attr.string(default = '*'),
},
)
```
`BUILD.bazel` file:
```python theme={null}
load('//:file_count.bzl', 'file_count_rule')
cc_library(
name = 'lib',
srcs = [
'lib.h',
'lib.cc',
],
)
cc_binary(
name = 'app',
srcs = [
'app.h',
'app.cc',
'main.cc',
],
deps = ['lib'],
)
file_count_rule(
name = 'file_count',
deps = ['app'],
extension = 'h',
)
```
### Aspect definition
```python theme={null}
file_count_aspect = aspect(
implementation = _file_count_aspect_impl,
attr_aspects = ['deps'],
attrs = {
'extension' : attr.string(values = ['*', 'h', 'cc']),
}
)
```
This example shows how the aspect propagates through the `deps` attribute.
`attrs` defines a set of attributes for an aspect. Public aspect attributes
define parameters and can only be of types `bool`, `int` or `string`.
For rule-propagated aspects, `int` and `string` parameters must have
`values` specified on them. This example has a parameter called `extension`
that is allowed to have '`*`', '`h`', or '`cc`' as a value.
For rule-propagated aspects, parameter values are taken from the rule requesting
the aspect, using the attribute of the rule that has the same name and type.
(see the definition of `file_count_rule`).
For command-line aspects, the parameters values can be passed using
[`--aspects_parameters`](/reference/command-line-reference#flag--aspects_parameters)
flag. The `values` restriction of `int` and `string` parameters may be
omitted.
Aspects are also allowed to have private attributes of types `label` or
`label_list`. Private label attributes can be used to specify dependencies on
tools or libraries that are needed for actions generated by aspects. There is not
a private attribute defined in this example, but the following code snippet
demonstrates how you could pass in a tool to an aspect:
```python theme={null}
...
attrs = {
'_protoc' : attr.label(
default = Label('//tools:protoc'),
executable = True,
cfg = "exec"
)
}
...
```
### Aspect implementation
```python theme={null}
FileCountInfo = provider(
fields = {
'count' : 'number of files'
}
)
def _file_count_aspect_impl(target, ctx):
count = 0
# Make sure the rule has a srcs attribute.
if hasattr(ctx.rule.attr, 'srcs'):
# Iterate through the sources counting files
for src in ctx.rule.attr.srcs:
for f in src.files.to_list():
if ctx.attr.extension == '*' or ctx.attr.extension == f.extension:
count = count + 1
# Get the counts from our dependencies.
for dep in ctx.rule.attr.deps:
count = count + dep[FileCountInfo].count
return [FileCountInfo(count = count)]
```
Just like a rule implementation function, an aspect implementation function
returns a struct of providers that are accessible to its dependencies.
In this example, the `FileCountInfo` is defined as a provider that has one
field `count`. It is best practice to explicitly define the fields of a
provider using the `fields` attribute.
The set of providers for an aspect application A(X) is the union of providers
that come from the implementation of a rule for target X and from the
implementation of aspect A. The providers that a rule implementation propagates
are created and frozen before aspects are applied and cannot be modified from an
aspect. It is an error if a target and an aspect that is applied to it each
provide a provider with the same type, with the exceptions of
[`OutputGroupInfo`](/rules/lib/providers/OutputGroupInfo)
(which is merged, so long as the
rule and aspect specify different output groups) and
[`InstrumentedFilesInfo`](/rules/lib/providers/InstrumentedFilesInfo)
(which is taken from the aspect). This means that aspect implementations may
never return [`DefaultInfo`](/rules/lib/providers/DefaultInfo).
The parameters and private attributes are passed in the attributes of the
`ctx`. This example references the `extension` parameter and determines
what files to count.
For returning providers, the values of attributes along which
the aspect is propagated (from the `attr_aspects` list) are replaced with
the results of an application of the aspect to them. For example, if target
X has Y and Z in its deps, `ctx.rule.attr.deps` for A(X) will be \[A(Y), A(Z)].
In this example, `ctx.rule.attr.deps` are Target objects that are the
results of applying the aspect to the 'deps' of the original target to which
the aspect has been applied.
In the example, the aspect accesses the `FileCountInfo` provider from the
target's dependencies to accumulate the total transitive number of files.
### Invoking the aspect from a rule
```python theme={null}
def _file_count_rule_impl(ctx):
for dep in ctx.attr.deps:
print(dep[FileCountInfo].count)
file_count_rule = rule(
implementation = _file_count_rule_impl,
attrs = {
'deps' : attr.label_list(aspects = [file_count_aspect]),
'extension' : attr.string(default = '*'),
},
)
```
The rule implementation demonstrates how to access the `FileCountInfo`
via the `ctx.attr.deps`.
The rule definition demonstrates how to define a parameter (`extension`)
and give it a default value (`*`). Note that having a default value that
was not one of '`cc`', '`h`', or '`*`' would be an error due to the
restrictions placed on the parameter in the aspect definition.
### Invoking an aspect through a target rule
```python theme={null}
load('//:file_count.bzl', 'file_count_rule')
cc_binary(
name = 'app',
...
)
file_count_rule(
name = 'file_count',
deps = ['app'],
extension = 'h',
)
```
This demonstrates how to pass the `extension` parameter into the aspect
via the rule. Since the `extension` parameter has a default value in the
rule implementation, `extension` would be considered an optional parameter.
When the `file_count` target is built, our aspect will be evaluated for
itself, and all of the targets accessible recursively via `deps`.
## References
* [`aspect` API reference](/rules/lib/globals/bzl#aspect)
# Automatic Execution Groups (AEGs)
Source: https://bazel.build/extending/auto-exec-groups
Automatic execution groups select an [execution platform][exec_platform]
for each toolchain type. In other words, one target can have multiple
execution platforms without defining execution groups.
## Quick summary
Automatic execution groups are closely connected to toolchains. If you are using
toolchains, you need to set them on the affected actions (actions which use an
executable or a tool from a toolchain) by adding `toolchain` parameter. For
example:
```python theme={null}
ctx.actions.run(
...,
executable = ctx.toolchain['@bazel_tools//tools/jdk:toolchain_type'].tool,
...,
toolchain = '@bazel_tools//tools/jdk:toolchain_type',
)
```
If the action does not use a tool or executable from a toolchain, and Blaze
doesn't detect that ([the error](#first-error-message) is raised), you can set
`toolchain = None`.
If you need to use multiple toolchains on a single execution platform (an action
uses executable or tools from two or more toolchains), you need to manually
define [exec\_groups][exec_groups]\(check [When should I use a custom exec\_group?][multiple_toolchains_exec_groups] section).
## History
Before AEGs, the execution platform was selected on a rule level. For example:
```python theme={null}
my_rule = rule(
_impl,
toolchains = ['//tools:toolchain_type_1', '//tools:toolchain_type_2'],
)
```
Rule `my_rule` registers two toolchain types. This means that the [Toolchain Resolution](https://bazel.build/extending/toolchains#toolchain-resolution) used
to find an execution platform which supports both toolchain types. The selected
execution platform was used for each registered action inside the rule, unless
specified differently with [exec\_groups][exec_groups].
In other words, all actions inside the rule used to have a single execution
platform even if they used tools from different toolchains (execution platform
is selected for each target). This resulted in failures when there was no
execution platform supporting all toolchains.
## Current state
With AEGs, the execution platform is selected for each toolchain type. The
implementation function of the earlier example, `my_rule`, would look like:
```python theme={null}
def _impl(ctx):
ctx.actions.run(
mnemonic = "First action",
executable = ctx.toolchain['//tools:toolchain_type_1'].tool,
toolchain = '//tools:toolchain_type_1',
)
ctx.actions.run(
mnemonic = "Second action",
executable = ctx.toolchain['//tools:toolchain_type_2'].tool,
toolchain = '//tools:toolchain_type_2',
)
```
This rule creates two actions, the `First action` which uses executable from a
`//tools:toolchain_type_1` and the `Second action` which uses executable from a
`//tools:toolchain_type_2`. Before AEGs, both of these actions would be executed
on a single execution platform which supports both toolchain types. With AEGs,
by adding the `toolchain` parameter inside the actions, each action executes on
the execution platform that provides the toolchain. The actions may be executed
on different execution platforms.
The same is effective with [ctx.actions.run\_shell][run_shell] where `toolchain`
parameter should be added when `tools` are from a toolchain.
## Difference between custom exec groups and automatic exec groups
As the name suggests, AEGs are exec groups created automatically for each
toolchain type registered on a rule. There is no need to manually specify them,
unlike the "classic" exec groups. Moreover, name of AEG is automatically set to
its toolchain type (e.g. `//tools:toolchain_type_1`).
### When should I use a custom exec\_group?
Custom exec\_groups are needed only in case where multiple toolchains need to
execute on a single execution platform. In all other cases there's no need to
define custom exec\_groups. For example:
```python theme={null}
def _impl(ctx):
ctx.actions.run(
...,
executable = ctx.toolchain['//tools:toolchain_type_1'].tool,
tools = [ctx.toolchain['//tools:toolchain_type_2'].tool],
exec_group = 'two_toolchains',
)
```
```python theme={null}
my_rule = rule(
_impl,
exec_groups = {
"two_toolchains": exec_group(
toolchains = ['//tools:toolchain_type_1', '//tools:toolchain_type_2'],
),
}
)
```
## Migration of AEGs
Internally in google3, Blaze is already using AEGs.
Externally for Bazel, migration is in the process. Some rules are already using
this feature (e.g. Java and C++ rules).
### Which Bazel versions support this migration?
AEGs are fully supported from Bazel 7.
### How to enable AEGs?
Set `--incompatible_auto_exec_groups` to true. More information about the flag
on [the GitHub issue][github_flag].
### How to enable AEGs inside a particular rule?
Set the `_use_auto_exec_groups` attribute on a rule.
```python theme={null}
my_rule = rule(
_impl,
attrs = {
"_use_auto_exec_groups": attr.bool(default = True),
}
)
```
This enables AEGs only in `my_rule` and its actions start using the new logic
when selecting the execution platform. Incompatible flag is overridden with this
attribute.
### How to disable AEGs in case of an error?
Set `--incompatible_auto_exec_groups` to false to completely disable AEGs in
your project ([flag's GitHub issue][github_flag]), or disable a particular rule
by setting `_use_auto_exec_groups` attribute to `False`
([more details about the attribute](#how-enable-particular-rule)).
### Error messages while migrating to AEGs
#### Couldn't identify if tools are from implicit dependencies or a toolchain. Please set the toolchain parameter. If you're not using a toolchain, set it to 'None'.
* In this case you get a stack of calls before the error happened and you can
clearly see which exact action needs the toolchain parameter. Check which
toolchain is used for the action and set it with the toolchain param. If no
toolchain is used inside the action for tools or executable, set it to
`None`.
#### Action declared for non-existent toolchain '\[toolchain\_type]'.
* This means that you've set the toolchain parameter on the action but didn't
register it on the rule. Register the toolchain or set `None` inside the action.
## Additional material
For more information, check design document:
[Automatic exec groups for toolchains][aegs_design_doc].
[exec_platform]: https://bazel.build/extending/platforms#:~:text=Execution%20%2D%20a%20platform%20on%20which%20build%20tools%20execute%20build%20actions%20to%20produce%20intermediate%20and%20final%20outputs.
[exec_groups]: https://bazel.build/extending/exec-groups
[github_flag]: https://github.com/bazelbuild/bazel/issues/17134
[aegs_design_doc]: https://docs.google.com/document/d/1-rbP_hmKs9D639YWw5F_JyxPxL2bi6dSmmvj_WXak9M/edit#heading=h.5mcn15i0e1ch
[run_shell]: https://bazel.build/rules/lib/builtins/actions#run_shell
[multiple_toolchains_exec_groups]: /extending/auto-exec-groups#when-should-use-exec-groups
# Extension Overview
Source: https://bazel.build/extending/concepts
This page describes how to extend the BUILD language using macros
and rules.
Bazel extensions are files ending in `.bzl`. Use a
[load statement](/concepts/build-files#load) to import a symbol from an extension.
Before learning the more advanced concepts, first:
* Read about the [Starlark language](/rules/language), used in both the
`BUILD` and `.bzl` files.
* Learn how you can [share variables](/build/share-variables)
between two `BUILD` files.
## Macros and rules
A macro is a function that instantiates rules. Macros come in two flavors:
[symbolic macros](/extending/macros) (new in Bazel 8) and [legacy macros](/extending/legacy-macros). The two flavors of macros are defined
differently, but behave almost the same from the point of view of a user. A
macro is useful when a `BUILD` file is getting too repetitive or too complex, as
it lets you reuse some code. The function is evaluated as soon as the `BUILD`
file is read. After the evaluation of the `BUILD` file, Bazel has little
information about macros. If your macro generates a `genrule`, Bazel will
behave *almost* as if you declared that `genrule` in the `BUILD` file. (The one
exception is that targets declared in a symbolic macro have [special visibility semantics](/extending/macros#visibility): a symbolic macro can hide its internal
targets from the rest of the package.)
A [rule](/extending/rules) is more powerful than a macro. It can access Bazel
internals and have full control over what is going on. It may for example pass
information to other rules.
If you want to reuse simple logic, start with a macro; we recommend a symbolic
macro, unless you need to support older Bazel versions. If a macro becomes
complex, it is often a good idea to make it a rule. Support for a new language
is typically done with a rule. Rules are for advanced users, and most users will
never have to write one; they will only load and call existing rules.
## Evaluation model
A build consists of three phases.
* **Loading phase**. First, load and evaluate all extensions and all `BUILD`
files that are needed for the build. The execution of the `BUILD` files simply
instantiates rules (each time a rule is called, it gets added to a graph).
This is where macros are evaluated.
* **Analysis phase**. The code of the rules is executed (their `implementation`
function), and actions are instantiated. An action describes how to generate
a set of outputs from a set of inputs, such as "run gcc on hello.c and get
hello.o". You must list explicitly which files will be generated before
executing the actual commands. In other words, the analysis phase takes
the graph generated by the loading phase and generates an action graph.
* **Execution phase**. Actions are executed, when at least one of their outputs is
required. If a file is missing or if a command fails to generate one output,
the build fails. Tests are also run during this phase.
Bazel uses parallelism to read, parse and evaluate the `.bzl` files and `BUILD`
files. A file is read at most once per build and the result of the evaluation is
cached and reused. A file is evaluated only once all its dependencies (`load()`
statements) have been resolved. By design, loading a `.bzl` file has no visible
side-effect, it only defines values and functions.
Bazel tries to be clever: it uses dependency analysis to know which files must
be loaded, which rules must be analyzed, and which actions must be executed. For
example, if a rule generates actions that you don't need for the current build,
they will not be executed.
## Creating extensions
* [Create your first macro](/rules/macro-tutorial) in order to reuse some code.
Then [learn more about macros](/extending/macros) and [using them to create "custom verbs"](/rules/verbs-tutorial).
* [Follow the rules tutorial](/rules/rules-tutorial) to get started with rules.
Next, you can read more about the [rules concepts](/extending/rules).
The two links below will be very useful when writing your own extensions. Keep
them within reach:
* The [API reference](/rules/lib)
* [Examples](https://github.com/bazelbuild/examples/tree/master/rules)
## Going further
In addition to [macros](/extending/macros) and [rules](/extending/rules), you
may want to write [aspects](/extending/aspects) and [repository rules](/external/repo).
* Use [Buildifier](https://github.com/bazelbuild/buildtools)
consistently to format and lint your code.
* Follow the [`.bzl` style guide](/rules/bzl-style).
* [Test](/rules/testing) your code.
* [Generate documentation](https://skydoc.bazel.build/) to help your users.
* [Optimize the performance](/rules/performance) of your code.
* [Deploy](/rules/deploying) your extensions to other people.
# Configurations
Source: https://bazel.build/extending/config
This page covers the benefits and basic usage of Starlark configurations,
Bazel's API for customizing how your project builds. It includes how to define
build settings and provides examples.
This makes it possible to:
* define custom flags for your project, obsoleting the need for
[`--define`](/docs/configurable-attributes#custom-keys)
* write
[transitions](/rules/lib/builtins/transition#transition) to configure deps in
different configurations than their parents
(such as `--compilation_mode=opt` or `--cpu=arm`)
* bake better defaults into rules (such as automatically build `//my:android_app`
with a specified SDK)
and more, all completely from .bzl files (no Bazel release required). See the
`bazelbuild/examples` repo for
[examples](https://github.com/bazelbuild/examples/tree/HEAD/configurations).
## User-defined build settings
A build setting is a single piece of
[configuration](/extending/rules#configurations)
information. Think of a configuration as a key/value map. Setting `--cpu=ppc`
and `--copt="-DFoo"` produces a configuration that looks like
`{cpu: ppc, copt: "-DFoo"}`. Each entry is a build setting.
Traditional flags like `cpu` and `copt` are native settings —
their keys are defined and their values are set inside native bazel java code.
Bazel users can only read and write them via the command line
and other APIs maintained natively. Changing native flags, and the APIs
that expose them, requires a bazel release. User-defined build
settings are defined in `.bzl` files (and thus, don't need a bazel release to
register changes). They also can be set via the command line
(if they're designated as `flags`, see more below), but can also be
set via [user-defined transitions](#user-defined-transitions).
### Defining build settings
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/basic_build_setting)
Note: Before defining your own build setting, check if one of the [predefined
settings](#predefined-settings) is suitable.
#### The `build_setting` `rule()` parameter
Build settings are rules like any other rule and are differentiated using the
Starlark `rule()` function's `build_setting`
[attribute](/rules/lib/globals/bzl#rule.build_setting).
```python theme={null}
# example/buildsettings/build_settings.bzl
string_flag = rule(
implementation = _impl,
build_setting = config.string(flag = True)
)
```
The `build_setting` attribute takes a function that designates the type of the
build setting. The type is limited to a set of basic Starlark types like
`bool` and `string`. See the `config` module
[documentation](/rules/lib/toplevel/config) for details. More complicated typing can be
done in the rule's implementation function. More on this below.
The `config` module's functions takes an optional boolean parameter, `flag`,
which is set to false by default. if `flag` is set to true, the build setting
can be set on the command line by users as well as internally by rule writers
via default values and [transitions](/rules/lib/builtins/transition#transition).
Not all settings should be settable by users. For example, if you as a rule
writer have some debug mode that you'd like to turn on inside test rules,
you don't want to give users the ability to indiscriminately turn on that
feature inside other non-test rules.
#### Using ctx.build\_setting\_value
Like all rules, build setting rules have [implementation functions](/extending/rules#implementation-function).
The basic Starlark-type value of the build settings can be accessed via the
`ctx.build_setting_value` method. This method is only available to
[`ctx`](/rules/lib/builtins/ctx) objects of build setting rules. These implementation
methods can directly forward the build settings value or do additional work on
it, like type checking or more complex struct creation. Here's how you would
implement an `enum`-typed build setting:
```python theme={null}
# example/buildsettings/build_settings.bzl
TemperatureProvider = provider(fields = ['type'])
temperatures = ["HOT", "LUKEWARM", "ICED"]
def _impl(ctx):
raw_temperature = ctx.build_setting_value
if raw_temperature not in temperatures:
fail(str(ctx.label) + " build setting allowed to take values {"
+ ", ".join(temperatures) + "} but was set to unallowed value "
+ raw_temperature)
return TemperatureProvider(type = raw_temperature)
temperature = rule(
implementation = _impl,
build_setting = config.string(flag = True)
)
```
Note: if a rule depends on a build setting, it will receive whatever providers
the build setting implementation function returns, like any other dependency.
But all other references to the value of the build setting (such as in transitions)
will see its basic Starlark-typed value, not this post implementation function
value.
#### Defining multi-set string flags
String settings have an additional `allow_multiple` parameter which allows the
flag to be set multiple times on the command line or in bazelrcs. Their default
value is still set with a string-typed attribute:
```python theme={null}
# example/buildsettings/build_settings.bzl
allow_multiple_flag = rule(
implementation = _impl,
build_setting = config.string(flag = True, allow_multiple = True)
)
```
```python theme={null}
# example/BUILD
load("//example/buildsettings:build_settings.bzl", "allow_multiple_flag")
allow_multiple_flag(
name = "roasts",
build_setting_default = "medium"
)
```
Each setting of the flag is treated as a single value:
```shell theme={null}
$ bazel build //my/target --//example:roasts=blonde \
--//example:roasts=medium,dark
```
The above is parsed to `{"//example:roasts": ["blonde", "medium,dark"]}` and
`ctx.build_setting_value` returns the list `["blonde", "medium,dark"]`.
#### Instantiating build settings
Rules defined with the `build_setting` parameter have an implicit mandatory
`build_setting_default` attribute. This attribute takes on the same type as
declared by the `build_setting` param.
```python theme={null}
# example/buildsettings/build_settings.bzl
FlavorProvider = provider(fields = ['type'])
def _impl(ctx):
return FlavorProvider(type = ctx.build_setting_value)
flavor = rule(
implementation = _impl,
build_setting = config.string(flag = True)
)
```
```python theme={null}
# example/BUILD
load("//example/buildsettings:build_settings.bzl", "flavor")
flavor(
name = "favorite_flavor",
build_setting_default = "APPLE"
)
```
#### Scope
Build settings are by default only applied to the `target` \[configuration]
(/extending/rules#configurations), and won't be applied to the `exec`
configuration. To have the build setting applied to both the `target` and `exec`
configurations set the `scope` attribute to `"universal"`.
```python theme={null}
# example/BUILD
load("@bazel_skylib//rules:common_settings.bzl", "bool_flag")
bool_flag(
name = "use_this_for_compiler_and_sources",
scope = "universal"
)
```
### Predefined settings
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/use_skylib_build_setting)
The
[Skylib](https://github.com/bazelbuild/bazel-skylib)
library includes a set of predefined settings you can instantiate without having
to write custom Starlark.
For example, to define a setting that accepts a limited set of string values:
```python theme={null}
# example/BUILD
load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
string_flag(
name = "myflag",
values = ["a", "b", "c"],
build_setting_default = "a",
)
```
For a complete list, see
[Common build setting rules](https://github.com/bazelbuild/bazel-skylib/blob/main/rules/common_settings.bzl).
### Using build settings
#### Depending on build settings
If a target would like to read a piece of configuration information, it can
directly depend on the build setting via a regular attribute dependency.
```python theme={null}
# example/rules.bzl
load("//example/buildsettings:build_settings.bzl", "FlavorProvider")
def _rule_impl(ctx):
if ctx.attr.flavor[FlavorProvider].type == "ORANGE":
...
drink_rule = rule(
implementation = _rule_impl,
attrs = {
"flavor": attr.label()
}
)
```
```python theme={null}
# example/BUILD
load("//example:rules.bzl", "drink_rule")
load("//example/buildsettings:build_settings.bzl", "flavor")
flavor(
name = "favorite_flavor",
build_setting_default = "APPLE"
)
drink_rule(
name = "my_drink",
flavor = ":favorite_flavor",
)
```
Languages may wish to create a canonical set of build settings which all rules
for that language depend on. Though the native concept of `fragments` no longer
exists as a hardcoded object in Starlark configuration world, one way to
translate this concept would be to use sets of common implicit attributes. For
example:
```python theme={null}
# kotlin/rules.bzl
_KOTLIN_CONFIG = {
"_compiler": attr.label(default = "//kotlin/config:compiler-flag"),
"_mode": attr.label(default = "//kotlin/config:mode-flag"),
...
}
...
kotlin_library = rule(
implementation = _rule_impl,
attrs = dicts.add({
"library-attr": attr.string()
}, _KOTLIN_CONFIG)
)
kotlin_binary = rule(
implementation = _binary_impl,
attrs = dicts.add({
"binary-attr": attr.label()
}, _KOTLIN_CONFIG)
```
#### Using build settings on the command line
Similar to most native flags, you can use the command line to set build settings
[that are marked as flags](#rule-parameter). The build
setting's name is its full target path using `name=value` syntax:
```shell theme={null}
$ bazel build //my/target --//example:string_flag=some-value # allowed
$ bazel build //my/target --//example:string_flag some-value # not allowed
```
Special boolean syntax is supported:
```shell theme={null}
$ bazel build //my/target --//example:boolean_flag
$ bazel build //my/target --no//example:boolean_flag
```
#### Using build setting aliases
You can set an alias for your build setting target path to make it easier to read
on the command line. Aliases function similarly to native flags and also make use
of the double-dash option syntax.
Set an alias by adding `--flag_alias=ALIAS_NAME=TARGET_PATH`
to your `.bazelrc` . For example, to set an alias to `coffee`:
```shell theme={null}
# .bazelrc
build --flag_alias=coffee=//experimental/user/starlark_configurations/basic_build_setting:coffee-temp
```
Best Practice: Setting an alias multiple times results in the most recent
one taking precedence. Use unique alias names to avoid unintended parsing results.
To make use of the alias, type it in place of the build setting target path.
With the above example of `coffee` set in the user's `.bazelrc`:
```shell theme={null}
$ bazel build //my/target --coffee=ICED
```
instead of
```shell theme={null}
$ bazel build //my/target --//experimental/user/starlark_configurations/basic_build_setting:coffee-temp=ICED
```
Best Practice: While it possible to set aliases on the command line, leaving them
in a `.bazelrc` reduces command line clutter.
### Label-typed build settings
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/label_typed_build_setting)
Unlike other build settings, label-typed settings cannot be defined using the
`build_setting` rule parameter. Instead, bazel has two built-in rules:
`label_flag` and `label_setting`. These rules forward the providers of the
actual target to which the build setting is set. `label_flag` and
`label_setting` can be read/written by transitions and `label_flag` can be set
by the user like other `build_setting` rules can. Their only difference is they
can't customely defined.
Label-typed settings will eventually replace the functionality of late-bound
defaults. Late-bound default attributes are Label-typed attributes whose
final values can be affected by configuration. In Starlark, this will replace
the [`configuration_field`](/rules/lib/globals/bzl#configuration_field)
API.
```python theme={null}
# example/rules.bzl
MyProvider = provider(fields = ["my_field"])
def _dep_impl(ctx):
return MyProvider(my_field = "yeehaw")
dep_rule = rule(
implementation = _dep_impl
)
def _parent_impl(ctx):
if ctx.attr.my_field_provider[MyProvider].my_field == "cowabunga":
...
parent_rule = rule(
implementation = _parent_impl,
attrs = { "my_field_provider": attr.label() }
)
```
```python theme={null}
# example/BUILD
load("//example:rules.bzl", "dep_rule", "parent_rule")
dep_rule(name = "dep")
parent_rule(name = "parent", my_field_provider = ":my_field_provider")
label_flag(
name = "my_field_provider",
build_setting_default = ":dep"
)
```
### Build settings and select()
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/select_on_build_setting)
Users can configure attributes on build settings by using
[`select()`](/reference/be/functions#select). Build setting targets can be passed to the `flag_values` attribute of
`config_setting`. The value to match to the configuration is passed as a
`String` then parsed to the type of the build setting for matching.
```python theme={null}
config_setting(
name = "my_config",
flag_values = {
"//example:favorite_flavor": "MANGO"
}
)
```
## User-defined transitions
A configuration
[transition](/rules/lib/builtins/transition#transition)
maps the transformation from one configured target to another within the
build graph.
Important: Transitions have [memory and performance impact](#memory-performance-considerations).
### Defining
Transitions define configuration changes between rules. For example, a request
like "compile my dependency for a different CPU than its parent" is handled by a
transition.
Formally, a transition is a function from an input configuration to one or more
output configurations. Most transitions are 1:1 such as "override the input
configuration with `--cpu=ppc`". 1:2+ transitions can also exist but come
with special restrictions.
In Starlark, transitions are defined much like rules, with a defining
`transition()`
[function](/rules/lib/builtins/transition#transition)
and an implementation function.
```python theme={null}
# example/transitions/transitions.bzl
def _impl(settings, attr):
_ignore = (settings, attr)
return {"//example:favorite_flavor" : "MINT"}
hot_chocolate_transition = transition(
implementation = _impl,
inputs = [],
outputs = ["//example:favorite_flavor"]
)
```
The `transition()` function takes in an implementation function, a set of
build settings to read(`inputs`), and a set of build settings to write
(`outputs`). The implementation function has two parameters, `settings` and
`attr`. `settings` is a dictionary `{String : Object}` of all settings declared
in the `inputs` parameter to `transition()`.
`attr` is a dictionary of attributes and values of the rule to which the
transition is attached. When attached as an
[outgoing edge transition](#outgoing-edge-transitions), the values of these
attributes are all configured post-select() resolution. When attached as
an [incoming edge transition](#incoming-edge-transitions), `attr` does not
include any attributes that use a selector to resolve their value. If an
incoming edge transition on `--foo` reads attribute `bar` and then also
selects on `--foo` to set attribute `bar`, then there's a chance for the
incoming edge transition to read the wrong value of `bar` in the transition.
Note: Since transitions are attached to rule definitions and `select()`s are
attached to rule instantiations (such as targets), errors related to `select()`s on
read attributes will pop up when users create targets rather than when rules are
written. It may be worth taking extra care to communicate to rule users which
attributes they should be wary of selecting on or taking other precautions.
The implementation function must return a dictionary (or list of
dictionaries, in the case of
transitions with multiple output configurations)
of new build settings values to apply. The returned dictionary keyset(s) must
contain exactly the set of build settings passed to the `outputs`
parameter of the transition function. This is true even if a build setting is
not actually changed over the course of the transition - its original value must
be explicitly passed through in the returned dictionary.
### Defining 1:2+ transitions
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/multi_arch_binary)
[Outgoing edge transition](#outgoing-edge-transitions) can map a single input
configuration to two or more output configurations. This is useful for defining
rules that bundle multi-architecture code.
1:2+ transitions are defined by returning a list of dictionaries in the
transition implementation function.
```python theme={null}
# example/transitions/transitions.bzl
def _impl(settings, attr):
_ignore = (settings, attr)
return [
{"//example:favorite_flavor" : "LATTE"},
{"//example:favorite_flavor" : "MOCHA"},
]
coffee_transition = transition(
implementation = _impl,
inputs = [],
outputs = ["//example:favorite_flavor"]
)
```
They can also set custom keys that the rule implementation function can use to
read individual dependencies:
```python theme={null}
# example/transitions/transitions.bzl
def _impl(settings, attr):
_ignore = (settings, attr)
return {
"Apple deps": {"//command_line_option:cpu": "ppc"},
"Linux deps": {"//command_line_option:cpu": "x86"},
}
multi_arch_transition = transition(
implementation = _impl,
inputs = [],
outputs = ["//command_line_option:cpu"]
)
```
### Attaching transitions
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/attaching_transitions_to_rules)
Transitions can be attached in two places: incoming edges and outgoing edges.
Effectively this means rules can transition their own configuration (incoming
edge transition) and transition their dependencies' configurations (outgoing
edge transition).
NOTE: There is currently no way to attach Starlark transitions to native rules.
If you need to do this, contact
[bazel-discuss@googlegroups.com](mailto:bazel-discuss@googlegroups.com)
for help with figuring out workarounds.
### Incoming edge transitions
Incoming edge transitions are activated by attaching a `transition` object
(created by `transition()`) to `rule()`'s `cfg` parameter:
```python theme={null}
# example/rules.bzl
load("example/transitions:transitions.bzl", "hot_chocolate_transition")
drink_rule = rule(
implementation = _impl,
cfg = hot_chocolate_transition,
...
```
Incoming edge transitions must be 1:1 transitions.
### Outgoing edge transitions
Outgoing edge transitions are activated by attaching a `transition` object
(created by `transition()`) to an attribute's `cfg` parameter:
```python theme={null}
# example/rules.bzl
load("example/transitions:transitions.bzl", "coffee_transition")
drink_rule = rule(
implementation = _impl,
attrs = { "dep": attr.label(cfg = coffee_transition)}
...
```
Outgoing edge transitions can be 1:1 or 1:2+.
See [Accessing attributes with transitions](#accessing-attributes-with-transitions)
for how to read these keys.
### Transitions on native options
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/transition_on_native_flag)
Starlark transitions can also declare reads and writes on native build
configuration options via a special prefix to the option name.
```python theme={null}
# example/transitions/transitions.bzl
def _impl(settings, attr):
_ignore = (settings, attr)
return {"//command_line_option:cpu": "k8"}
cpu_transition = transition(
implementation = _impl,
inputs = [],
outputs = ["//command_line_option:cpu"]
```
#### Unsupported native options
Bazel doesn't support transitioning on `--define` with
`"//command_line_option:define"`. Instead, use a custom
[build setting](#user-defined-build-settings). In general, new usages of
`--define` are discouraged in favor of build settings.
Bazel doesn't support transitioning on `--config`. This is because `--config` is
an "expansion" flag that expands to other flags.
Crucially, `--config` may include flags that don't affect build configuration,
such as
[`--spawn_strategy`](/docs/user-manual#spawn-strategy)
. Bazel, by design, can't bind such flags to individual targets. This means
there's no coherent way to apply them in transitions.
As a workaround, you can explicitly itemize the flags that *are* part of
the configuration in your transition. This requires maintaining the `--config`'s
expansion in two places, which is a known UI blemish.
### Transitions on allow multiple build settings
When setting build settings that
[allow multiple values](#defining-multi-set-string-flags), the value of the
setting must be set with a list.
```python theme={null}
# example/buildsettings/build_settings.bzl
string_flag = rule(
implementation = _impl,
build_setting = config.string(flag = True, allow_multiple = True)
)
```
```python theme={null}
# example/BUILD
load("//example/buildsettings:build_settings.bzl", "string_flag")
string_flag(name = "roasts", build_setting_default = "medium")
```
```python theme={null}
# example/transitions/rules.bzl
def _transition_impl(settings, attr):
# Using a value of just "dark" here will throw an error
return {"//example:roasts" : ["dark"]},
coffee_transition = transition(
implementation = _transition_impl,
inputs = [],
outputs = ["//example:roasts"]
)
```
### No-op transitions
If a transition returns `{}`, `[]`, or `None`, this is shorthand for keeping all
settings at their original values. This can be more convenient than explicitly
setting each output to itself.
```python theme={null}
# example/transitions/transitions.bzl
def _impl(settings, attr):
_ignore = (attr)
if settings["//example:already_chosen"] is True:
return {}
return {
"//example:favorite_flavor": "dark chocolate",
"//example:include_marshmallows": "yes",
"//example:desired_temperature": "38C",
}
hot_chocolate_transition = transition(
implementation = _impl,
inputs = ["//example:already_chosen"],
outputs = [
"//example:favorite_flavor",
"//example:include_marshmallows",
"//example:desired_temperature",
]
)
```
### Composing transitions
Two transitions can be combined into a single new transition using
[`transition.and_then`](/rules/lib/builtins/transition#and_then):
```python theme={null}
combined_transition = first_transition.and_then(second_transition)
```
The composition applies `first_transition` to the input configuration and then
runs `second_transition` against each of its output configurations. The original
transitions are not modified, and the result is itself a `transition` object
that can be composed further with another `and_then` call.
A composed transition can be attached to a rule or attribute wherever its
component transitions could be used (subject to the usual restriction that an
[incoming edge transition](#incoming-edge-transitions) must be 1:1). At most one
of the composed transitions may be an exec transition (`"exec"` or
[`config.exec`](/rules/lib/toplevel/config#exec)).
When two of the composed transitions are 1:2+, the composition produces the
cross product of their splits. The key for each combined split is the
comma-separated concatenation of the component keys: if the first transition
produces keys `{a, b}` and the second produces `{x, y}` for each of those, the
composition produces the four keys `a,x`, `a,y`, `b,x`, and `b,y`. Note that
each additional 1:2+ transition multiplies the resulting dependency count, so
chain them with care.
### Accessing attributes with transitions
[End to end example](https://github.com/bazelbuild/examples/tree/HEAD/configurations/read_attr_in_transition)
When [attaching a transition to an outgoing edge](#outgoing-edge-transitions)
(regardless of whether the transition is a 1:1 or 1:2+ transition), `ctx.attr` is forced to be a list
if it isn't already. The order of elements in this list is unspecified.
```python theme={null}
# example/transitions/rules.bzl
def _transition_impl(settings, attr):
return {"//example:favorite_flavor" : "LATTE"},
coffee_transition = transition(
implementation = _transition_impl,
inputs = [],
outputs = ["//example:favorite_flavor"]
)
def _rule_impl(ctx):
# Note: List access even though "dep" is not declared as list
transitioned_dep = ctx.attr.dep[0]
# Note: Access doesn't change, other_deps was already a list
for other_dep in ctx.attr.other_deps:
# ...
coffee_rule = rule(
implementation = _rule_impl,
attrs = {
"dep": attr.label(cfg = coffee_transition)
"other_deps": attr.label_list(cfg = coffee_transition)
})
```
If the transition is `1:2+` and sets custom keys, `ctx.split_attr` can be used
to read individual deps for each key:
```python theme={null}
# example/transitions/rules.bzl
def _impl(settings, attr):
_ignore = (settings, attr)
return {
"Apple deps": {"//command_line_option:cpu": "ppc"},
"Linux deps": {"//command_line_option:cpu": "x86"},
}
multi_arch_transition = transition(
implementation = _impl,
inputs = [],
outputs = ["//command_line_option:cpu"]
)
def _rule_impl(ctx):
apple_dep = ctx.split_attr.dep["Apple deps"]
linux_dep = ctx.split_attr.dep["Linux deps"]
# ctx.attr has a list of all deps for all keys. Order is not guaranteed.
all_deps = ctx.attr.dep
multi_arch_rule = rule(
implementation = _rule_impl,
attrs = {
"dep": attr.label(cfg = multi_arch_transition)
})
```
See [complete example](https://github.com/bazelbuild/examples/tree/main/configurations/multi_arch_binary)
here.
## Integration with platforms and toolchains
Many native flags today, like `--cpu` and `--crosstool_top` are related to
toolchain resolution. In the future, explicit transitions on these types of
flags will likely be replaced by transitioning on the
[target platform](/extending/platforms).
## Memory and performance considerations
Adding transitions, and therefore new configurations, to your build comes at a
cost: larger build graphs, less comprehensible build graphs, and slower
builds. It's worth considering these costs when considering
using transitions in your build rules. Below is an example of how a transition
might create exponential growth of your build graph.
### Badly behaved builds: a case study
**Figure 1.** Scalability graph showing a top level target and its dependencies.
This graph shows a top level target, `//pkg:app`, which depends on two targets, a
`//pkg:1_0` and `//pkg:1_1`. Both these targets depend on two targets, `//pkg:2_0` and
`//pkg:2_1`. Both these targets depend on two targets, `//pkg:3_0` and `//pkg:3_1`.
This continues on until `//pkg:n_0` and `//pkg:n_1`, which both depend on a single
target, `//pkg:dep`.
Building `//pkg:app` requires \\(2n+2\\) targets:
* `//pkg:app`
* `//pkg:dep`
* `//pkg:i_0` and `//pkg:i_1` for \\(i\\) in \\(\[1..n]\\)
Imagine you [implement](#user-defined-build-settings) a flag
`--//foo:owner=` and `//pkg:i_b` applies
depConfig = myConfig + depConfig.owner="$(myConfig.owner)$(b)"
In other words, `//pkg:i_b` appends `b` to the old value of `--owner` for all
its deps.
This produces the following [configured targets](/reference/glossary#configured-target):
```
//pkg:app //foo:owner=""
//pkg:1_0 //foo:owner=""
//pkg:1_1 //foo:owner=""
//pkg:2_0 (via //pkg:1_0) //foo:owner="0"
//pkg:2_0 (via //pkg:1_1) //foo:owner="1"
//pkg:2_1 (via //pkg:1_0) //foo:owner="0"
//pkg:2_1 (via //pkg:1_1) //foo:owner="1"
//pkg:3_0 (via //pkg:1_0 → //pkg:2_0) //foo:owner="00"
//pkg:3_0 (via //pkg:1_0 → //pkg:2_1) //foo:owner="01"
//pkg:3_0 (via //pkg:1_1 → //pkg:2_0) //foo:owner="10"
//pkg:3_0 (via //pkg:1_1 → //pkg:2_1) //foo:owner="11"
...
```
`//pkg:dep` produces \\(2^n\\) configured targets: `config.owner=`
"\\(b\_0b\_1...b\_n\\)" for all \\(b\_i\\) in \\(\{0,1}\\).
This makes the build graph exponentially larger than the target graph, with
corresponding memory and performance consequences.
TODO: Add strategies for measurement and mitigation of these issues.
## Further reading
For more details on modifying build configurations, see:
* [Starlark Build Configuration](https://docs.google.com/document/d/1vc8v-kXjvgZOdQdnxPTaV0rrLxtP2XwnD2tAZlYJOqw/edit?usp=sharing)
* Full [set](https://github.com/bazelbuild/examples/tree/HEAD/configurations) of end to end examples
# Depsets
Source: https://bazel.build/extending/depsets
[Depsets](/rules/lib/builtins/depset) are a specialized data structure for efficiently
collecting data across a target’s transitive dependencies. They are an essential
element of rule processing.
The defining feature of depset is its time- and space-efficient union operation.
The depset constructor accepts a list of elements ("direct") and a list of other
depsets ("transitive"), and returns a depset representing a set containing all the
direct elements and the union of all the transitive sets. Conceptually, the
constructor creates a new graph node that has the direct and transitive nodes
as its successors. Depsets have a well-defined ordering semantics, based on
traversal of this graph.
Example uses of depsets include:
* Storing the paths of all object files for a program’s libraries, which can
then be passed to a linker action through a provider.
* For an interpreted language, storing the transitive source files that are
included in an executable's runfiles.
## Description and operations
Conceptually, a depset is a directed acyclic graph (DAG) that typically looks
similar to the target graph. It is constructed from the leaves up to the root.
Each target in a dependency chain can add its own contents on top of the
previous without having to read or copy them.
Each node in the DAG holds a list of direct elements and a list of child nodes.
The contents of the depset are the transitive elements, such as the direct elements
of all the nodes. A new depset can be created using the
[depset](/rules/lib/globals/bzl#depset) constructor: it accepts a list of direct
elements and another list of child nodes.
```python theme={null}
s = depset(["a", "b", "c"])
t = depset(["d", "e"], transitive = [s])
print(s) # depset(["a", "b", "c"])
print(t) # depset(["d", "e", "a", "b", "c"])
```
To retrieve the contents of a depset, use the
[to\_list()](/rules/lib/builtins/depset#to_list) method. It returns a list of all transitive
elements, not including duplicates. There is no way to directly inspect the
precise structure of the DAG, although this structure does affect the order in
which the elements are returned.
```python theme={null}
s = depset(["a", "b", "c"])
print("c" in s.to_list()) # True
print(s.to_list() == ["a", "b", "c"]) # True
```
The allowed items in a depset are restricted, just as the allowed keys in
dictionaries are restricted. In particular, depset contents may not be mutable.
Depsets use reference equality: a depset is equal to itself, but unequal to any
other depset, even if they have the same contents and same internal structure.
```python theme={null}
s = depset(["a", "b", "c"])
t = s
print(s == t) # True
t = depset(["a", "b", "c"])
print(s == t) # False
d = {}
d[s] = None
d[t] = None
print(len(d)) # 2
```
To compare depsets by their contents, convert them to sorted lists.
```python theme={null}
s = depset(["a", "b", "c"])
t = depset(["c", "b", "a"])
print(sorted(s.to_list()) == sorted(t.to_list())) # True
```
There is no ability to remove elements from a depset. If this is needed, you
must read out the entire contents of the depset, filter the elements you want to
remove, and reconstruct a new depset. This is not particularly efficient.
```python theme={null}
s = depset(["a", "b", "c"])
t = depset(["b", "c"])
# Compute set difference s - t. Precompute t.to_list() so it's not done
# in a loop, and convert it to a dictionary for fast membership tests.
t_items = {e: None for e in t.to_list()}
diff_items = [x for x in s.to_list() if x not in t_items]
# Convert back to depset if it's still going to be used for union operations.
s = depset(diff_items)
print(s) # depset(["a"])
```
### Order
The `to_list` operation performs a traversal over the DAG. The kind of traversal
depends on the *order* that was specified at the time the depset was
constructed. It is useful for Bazel to support multiple orders because sometimes
tools care about the order of their inputs. For example, a linker action may
need to ensure that if `B` depends on `A`, then `A.o` comes before `B.o` on the
linker’s command line. Other tools might have the opposite requirement.
Three traversal orders are supported: `postorder`, `preorder`, and
`topological`. The first two work exactly like [tree traversals](https://en.wikipedia.org/wiki/Tree_traversal#Depth-first_search)
except that they operate on DAGs and skip already visited nodes. The third order
works as a topological sort from root to leaves, essentially the same as
preorder except that shared children are listed only after all of their parents.
Preorder and postorder operate as left-to-right traversals, but note that within
each node direct elements have no order relative to children. For topological
order, there is no left-to-right guarantee, and even the
all-parents-before-child guarantee does not apply in the case that there are
duplicate elements in different nodes of the DAG.
```python theme={null}
# This demonstrates different traversal orders.
def create(order):
cd = depset(["c", "d"], order = order)
gh = depset(["g", "h"], order = order)
return depset(["a", "b", "e", "f"], transitive = [cd, gh], order = order)
print(create("postorder").to_list()) # ["c", "d", "g", "h", "a", "b", "e", "f"]
print(create("preorder").to_list()) # ["a", "b", "e", "f", "c", "d", "g", "h"]
```
```python theme={null}
# This demonstrates different orders on a diamond graph.
def create(order):
a = depset(["a"], order=order)
b = depset(["b"], transitive = [a], order = order)
c = depset(["c"], transitive = [a], order = order)
d = depset(["d"], transitive = [b, c], order = order)
return d
print(create("postorder").to_list()) # ["a", "b", "c", "d"]
print(create("preorder").to_list()) # ["d", "b", "a", "c"]
print(create("topological").to_list()) # ["d", "b", "c", "a"]
```
Due to how traversals are implemented, the order must be specified at the time
the depset is created with the constructor’s `order` keyword argument. If this
argument is omitted, the depset has the special `default` order, in which case
there are no guarantees about the order of any of its elements (except that it
is deterministic).
## Full example
This example is available at
[https://github.com/bazelbuild/examples/tree/main/rules/depsets](https://github.com/bazelbuild/examples/tree/main/rules/depsets).
Suppose there is a hypothetical interpreted language Foo. In order to build
each `foo_binary` you need to know all the `*.foo` files that it directly or
indirectly depends on.
```python theme={null}
# //depsets:BUILD
load(":foo.bzl", "foo_library", "foo_binary")
# Our hypothetical Foo compiler.
py_binary(
name = "foocc",
srcs = ["foocc.py"],
)
foo_library(
name = "a",
srcs = ["a.foo", "a_impl.foo"],
)
foo_library(
name = "b",
srcs = ["b.foo", "b_impl.foo"],
deps = [":a"],
)
foo_library(
name = "c",
srcs = ["c.foo", "c_impl.foo"],
deps = [":a"],
)
foo_binary(
name = "d",
srcs = ["d.foo"],
deps = [":b", ":c"],
)
```
```python theme={null}
# //depsets:foocc.py
# "Foo compiler" that just concatenates its inputs to form its output.
import sys
if __name__ == "__main__":
assert len(sys.argv) >= 1
output = open(sys.argv[1], "wt")
for path in sys.argv[2:]:
input = open(path, "rt")
output.write(input.read())
```
Here, the transitive sources of the binary `d` are all of the `*.foo` files in
the `srcs` fields of `a`, `b`, `c`, and `d`. In order for the `foo_binary`
target to know about any file besides `d.foo`, the `foo_library` targets need to
pass them along in a provider. Each library receives the providers from its own
dependencies, adds its own immediate sources, and passes on a new provider with
the augmented contents. The `foo_binary` rule does the same, except that instead
of returning a provider, it uses the complete list of sources to construct a
command line for an action.
Here’s a complete implementation of the `foo_library` and `foo_binary` rules.
```python theme={null}
# //depsets/foo.bzl
# A provider with one field, transitive_sources.
foo_files = provider(fields = ["transitive_sources"])
def get_transitive_srcs(srcs, deps):
"""Obtain the source files for a target and its transitive dependencies.
Args:
srcs: a list of source files
deps: a list of targets that are direct dependencies
Returns:
a collection of the transitive sources
"""
return depset(
srcs,
transitive = [dep[foo_files].transitive_sources for dep in deps])
def _foo_library_impl(ctx):
trans_srcs = get_transitive_srcs(ctx.files.srcs, ctx.attr.deps)
return [foo_files(transitive_sources=trans_srcs)]
foo_library = rule(
implementation = _foo_library_impl,
attrs = {
"srcs": attr.label_list(allow_files=True),
"deps": attr.label_list(),
},
)
def _foo_binary_impl(ctx):
foocc = ctx.executable._foocc
out = ctx.outputs.out
trans_srcs = get_transitive_srcs(ctx.files.srcs, ctx.attr.deps)
srcs_list = trans_srcs.to_list()
ctx.actions.run(executable = foocc,
arguments = [out.path] + [src.path for src in srcs_list],
inputs = srcs_list + [foocc],
outputs = [out])
foo_binary = rule(
implementation = _foo_binary_impl,
attrs = {
"srcs": attr.label_list(allow_files=True),
"deps": attr.label_list(),
"_foocc": attr.label(default=Label("//depsets:foocc"),
allow_files=True, executable=True, cfg="host")
},
outputs = {"out": "%{name}.out"},
)
```
You can test this by copying these files into a fresh package, renaming the
labels appropriately, creating the source `*.foo` files with dummy content, and
building the `d` target.
## Performance
To see the motivation for using depsets, consider what would happen if
`get_transitive_srcs()` collected its sources in a list.
```python theme={null}
def get_transitive_srcs(srcs, deps):
trans_srcs = []
for dep in deps:
trans_srcs += dep[foo_files].transitive_sources
trans_srcs += srcs
return trans_srcs
```
This does not take into account duplicates, so the source files for `a`
will appear twice on the command line and twice in the contents of the output
file.
An alternative is using a general set, which can be simulated by a
dictionary where the keys are the elements and all the keys map to `True`.
```python theme={null}
def get_transitive_srcs(srcs, deps):
trans_srcs = {}
for dep in deps:
for file in dep[foo_files].transitive_sources:
trans_srcs[file] = True
for file in srcs:
trans_srcs[file] = True
return trans_srcs
```
This gets rid of the duplicates, but it makes the order of the command line
arguments (and therefore the contents of the files) unspecified, although still
deterministic.
Moreover, both approaches are asymptotically worse than the depset-based
approach. Consider the case where there is a long chain of dependencies on
Foo libraries. Processing every rule requires copying all of the transitive
sources that came before it into a new data structure. This means that the
time and space cost for analyzing an individual library or binary target
is proportional to its own height in the chain. For a chain of length n,
foolib\_1 ← foolib\_2 ← … ← foolib\_n, the overall cost is effectively O(n^2).
Generally speaking, depsets should be used whenever you are accumulating
information through your transitive dependencies. This helps ensure that
your build scales well as your target graph grows deeper.
Finally, it’s important to not retrieve the contents of the depset
unnecessarily in rule implementations. Calling `to_list()` at the end in a
single binary rule avoids quadratic behavior across the chain of library rules
(since the cost is just O(n) for that target in isolation). However, doing so
across multiple top-level targets with overlapping dependencies (such as when
building `//foo/tests/...` or importing an IDE project) still results in O(n^2)
cost. Whenever possible, avoid calling `to_list()` altogether; for example, pass
depsets directly to `ctx.actions.args()` to defer expansion to the execution
phase.
For more information about using depsets efficiently, see the [performance](/rules/performance#avoid-depset-to-list) page.
## API Reference
Please see [here](/rules/lib/builtins/depset) for more details.
# Execution Groups
Source: https://bazel.build/extending/exec-groups
Execution groups allow for multiple execution platforms within a single target.
Each execution group has its own [toolchain](/extending/toolchains) dependencies and
performs its own [toolchain resolution](/extending/toolchains#toolchain-resolution).
## Current status
Execution groups for certain natively declared actions, like `CppLink`, can be
used inside `exec_properties` to set per-action, per-target execution
requirements. For more details, see the
[Default execution groups](#exec-groups-for-native-rules) section.
## Background
Execution groups allow the rule author to define sets of actions, each with a
potentially different execution platform. Multiple execution platforms can allow
actions to execute differently, for example compiling an iOS app on a remote
(linux) worker and then linking/code signing on a local mac worker.
Being able to define groups of actions also helps alleviate the usage of action
mnemonics as a proxy for specifying actions. Mnemonics are not guaranteed to be
unique and can only reference a single action. This is especially helpful in
allocating extra resources to specific memory and processing intensive actions
like linking in C++ builds without over-allocating to less demanding tasks.
## Defining execution groups
During rule definition, rule authors can
[declare](/rules/lib/globals/bzl#exec_group)
a set of execution groups. On each execution group, the rule author can specify
everything needed to select an execution platform for that execution group,
namely any constraints via `exec_compatible_with` and toolchain types via
`toolchain`.
```python theme={null}
# foo.bzl
my_rule = rule(
_impl,
exec_groups = {
"link": exec_group(
exec_compatible_with = ["@platforms//os:linux"],
toolchains = ["//foo:toolchain_type"],
),
"test": exec_group(
toolchains = ["//foo_tools:toolchain_type"],
),
},
attrs = {
"_compiler": attr.label(cfg = config.exec("link"))
},
)
```
In the code snippet above, you can see that tool dependencies can also specify
transition for an exec group using the
[`cfg`](/rules/lib/toplevel/attr#label)
attribute param and the
[`config`](/rules/lib/toplevel/config)
module. The module exposes an `exec` function which takes a single string
parameter which is the name of the exec group for which the dependency should be
built.
As on native rules, the `test` execution group is present by default on Starlark
test rules.
## Accessing execution groups
In the rule implementation, you can declare that actions should be run on the
execution platform of an execution group. You can do this by using the `exec_group`
param of action generating methods, specifically [`ctx.actions.run`](/rules/lib/builtins/actions#run) and
[`ctx.actions.run_shell`](/rules/lib/builtins/actions#run_shell).
```python theme={null}
# foo.bzl
def _impl(ctx):
ctx.actions.run(
inputs = [ctx.attr._some_tool, ctx.srcs[0]]
exec_group = "compile",
# ...
)
```
Rule authors will also be able to access the [resolved toolchains](/extending/toolchains#toolchain-resolution)
of execution groups, similarly to how you
can access the resolved toolchain of a target:
```python theme={null}
# foo.bzl
def _impl(ctx):
foo_info = ctx.exec_groups["link"].toolchains["//foo:toolchain_type"].fooinfo
ctx.actions.run(
inputs = [foo_info, ctx.srcs[0]]
exec_group = "link",
# ...
)
```
Note: If an action uses a toolchain from an execution group, but doesn't specify
that execution group in the action declaration, that may potentially cause
issues. A mismatch like this may not immediately cause failures, but is a latent
problem.
### Default execution groups
The following execution groups are predefined:
* `test`: Test runner actions (for more details, see
the [execution platform section of the Test Encyclopedia](/reference/test-encyclopedia#execution-platform)).
* `cpp_link`: C++ linking actions.
## Using execution groups to set execution properties
Execution groups are integrated with the
[`exec_properties`](/reference/be/common-definitions#common-attributes)
attribute that exists on every rule and allows the target writer to specify a
string dict of properties that is then passed to the execution machinery. For
example, if you wanted to set some property, say memory, for the target and give
certain actions a higher memory allocation, you would write an `exec_properties`
entry with an execution-group-augmented key, such as:
```python theme={null}
# BUILD
my_rule(
name = 'my_target',
exec_properties = {
'mem': '12g',
'link.mem': '16g'
}
…
)
```
All actions with `exec_group = "link"` would see the exec properties
dictionary as `{"mem": "16g"}`. As you see here, execution-group-level
settings override target-level settings.
## Using execution groups to set platform constraints
Execution groups are also integrated with the
[`exec_compatible_with`](/reference/be/common-definitions#common-attributes) and
[`exec_group_compatible_with`](/reference/be/common-definitions#common-attributes)
attributes that exist on every rule and allow the target writer to specify
additional constraints that must be satisfied by the execution platforms
selected for the target's actions.
For example, if the rule `my_test` defines the `link` execution group in
addition to the default and the `test` execution group, then the following
usage of these attributes would run actions in the default execution group on
a platform with a high number of CPUs, the test action on Linux, and the link
action on the default execution platform:
```python theme={null}
# BUILD
constraint_setting(name = "cpu")
constraint_value(name = "high_cpu", constraint_setting = ":cpu")
platform(
name = "high_cpu_platform",
constraint_values = [":high_cpu"],
exec_properties = {
"cpu": "256",
},
)
my_test(
name = "my_test",
exec_compatible_with = ["//constraints:high_cpu"],
exec_group_compatible_with = {
"test": ["@platforms//os:linux"],
},
...
)
```
### Execution groups for native rules
The following execution groups are available for actions defined by native
rules:
* `test`: Test runner actions.
* `cpp_link`: C++ linking actions.
### Execution groups and platform execution properties
It is possible to define `exec_properties` for arbitrary execution groups on
platform targets (unlike `exec_properties` set directly on a target, where
properties for unknown execution groups are rejected). Targets then inherit the
execution platform's `exec_properties` that affect the default execution group
and any other relevant execution groups.
For example, suppose running tests on the exec platform requires some resource
to be available, but it isn't required for compiling and linking; this can be
modelled as follows:
```python theme={null}
constraint_setting(name = "resource")
constraint_value(name = "has_resource", constraint_setting = ":resource")
platform(
name = "platform_with_resource",
constraint_values = [":has_resource"],
exec_properties = {
"test.resource": "...",
},
)
cc_test(
name = "my_test",
srcs = ["my_test.cc"],
exec_compatible_with = [":has_resource"],
)
```
`exec_properties` defined directly on targets take precedence over those that
are inherited from the execution platform.
# Legacy Macros
Source: https://bazel.build/extending/legacy-macros
Legacy macros are unstructured functions called from `BUILD` files that can
create targets. By the end of the
[loading phase](/extending/concepts#evaluation-model), legacy macros don't exist
anymore, and Bazel sees only the concrete set of instantiated rules.
## Why you shouldn't use legacy macros (and should use Symbolic macros instead)
Where possible you should use [symbolic macros](/extending/macros#macros).
Symbolic macros
* Prevent action at a distance
* Make it possible to hide implementation details through granular visibility
* Take typed attributes, which in turn means automatic label and select
conversion.
* Are more readable
* Will soon have [lazy evaluation](/extending/macros#laziness)
## Usage
The typical use case for a macro is when you want to reuse a rule.
For example, genrule in a `BUILD` file generates a file using `//:generator`
with a `some_arg` argument hardcoded in the command:
```python theme={null}
genrule(
name = "file",
outs = ["file.txt"],
cmd = "$(location //:generator) some_arg > $@",
tools = ["//:generator"],
)
```
Note: `$@` is a
[Make variable](/reference/be/make-variables#predefined_genrule_variables) that
refers to the execution-time locations of the files in the `outs` attribute
list. It is equivalent to `$(locations :file.txt)`.
If you want to generate more files with different arguments, you may want to
extract this code to a macro function. To create a macro called
`file_generator`, which has `name` and `arg` parameters, we can replace the
genrule with the following:
```python theme={null}
load("//path:generator.bzl", "file_generator")
file_generator(
name = "file",
arg = "some_arg",
)
file_generator(
name = "file-two",
arg = "some_arg_two",
)
file_generator(
name = "file-three",
arg = "some_arg_three",
)
```
Here, you load the `file_generator` symbol from a `.bzl` file located in the
`//path` package. By putting macro function definitions in a separate `.bzl`
file, you keep your `BUILD` files clean and declarative, The `.bzl` file can be
loaded from any package in the workspace.
Finally, in `path/generator.bzl`, write the definition of the macro to
encapsulate and parameterize the original genrule definition:
```python theme={null}
def file_generator(name, arg, visibility=None):
native.genrule(
name = name,
outs = [name + ".txt"],
cmd = "$(location //:generator) %s > $@" % arg,
tools = ["//:generator"],
visibility = visibility,
)
```
You can also use macros to chain rules together. This example shows chained
genrules, where a genrule uses the outputs of a previous genrule as inputs:
```python theme={null}
def chained_genrules(name, visibility=None):
native.genrule(
name = name + "-one",
outs = [name + ".one"],
cmd = "$(location :tool-one) $@",
tools = [":tool-one"],
visibility = ["//visibility:private"],
)
native.genrule(
name = name + "-two",
srcs = [name + ".one"],
outs = [name + ".two"],
cmd = "$(location :tool-two) $< $@",
tools = [":tool-two"],
visibility = visibility,
)
```
The example only assigns a visibility value to the second genrule. This allows
macro authors to hide the outputs of intermediate rules from being depended upon
by other targets in the workspace.
Note: Similar to `$@` for outputs, `$<` expands to the locations of files in the
`srcs` attribute list.
## Expanding macros
When you want to investigate what a macro does, use the `query` command with
`--output=build` to see the expanded form:
```none theme={null}
$ bazel query --output=build :file
# /absolute/path/test/ext.bzl:42:3
genrule(
name = "file",
tools = ["//:generator"],
outs = ["//test:file.txt"],
cmd = "$(location //:generator) some_arg > $@",
)
```
## Instantiating native rules
Native rules (rules that don't need a `load()` statement) can be instantiated
from the [native](/rules/lib/toplevel/native) module:
```python theme={null}
def my_macro(name, visibility=None):
native.cc_library(
name = name,
srcs = ["main.cc"],
visibility = visibility,
)
```
If you need to know the package name (for example, which `BUILD` file is calling
the macro), use the function
[native.package\_name()](/rules/lib/toplevel/native#package_name). Note that
`native` can only be used in `.bzl` files, and not in `BUILD` files.
## Label resolution in macros
Since legacy macros are evaluated in the
[loading phase](/extending/concepts#evaluation-model), label strings such as
`"//foo:bar"` that occur in a legacy macro are interpreted relative to the
`BUILD` file in which the macro is used rather than relative to the `.bzl` file
in which it is defined. This behavior is generally undesirable for macros that
are meant to be used in other repositories, such as because they are part of a
published Starlark ruleset.
To get the same behavior as for Starlark rules, wrap the label strings with the
[`Label`](/rules/lib/builtins/Label#Label) constructor:
```python theme={null}
# @my_ruleset//rules:defs.bzl
def my_cc_wrapper(name, deps = [], **kwargs):
native.cc_library(
name = name,
deps = deps + select({
# Due to the use of Label, this label is resolved within @my_ruleset,
# regardless of its site of use.
Label("//config:needs_foo"): [
# Due to the use of Label, this label will resolve to the correct target
# even if the canonical name of @dep_of_my_ruleset should be different
# in the main repo, such as due to repo mappings.
Label("@dep_of_my_ruleset//tools:foo"),
],
"//conditions:default": [],
}),
**kwargs,
)
```
With the `--incompatible_resolve_select_keys_eagerly` flag enabled, all keys
that are label strings will be automatically resolved to `Label` objects
relative to the package of the file that contains the `select` call. If this is
not chosen, wrap the label string with
[native.package\_relative\_label()](/rules/lib/toplevel/native#package_relative_label).
## Debugging
* `bazel query --output=build //my/path:all` will show you how the `BUILD`
file looks after evaluation. All legacy macros, globs, loops are expanded.
Known limitation: `select` expressions are not shown in the output.
* You may filter the output based on `generator_function` (which function
generated the rules) or `generator_name` (the name attribute of the macro):
`bash $ bazel query --output=build 'attr(generator_function, my_macro,
//my/path:all)'`
* To find out where exactly the rule `foo` is generated in a `BUILD` file, you
can try the following trick. Insert this line near the top of the `BUILD`
file: `cc_library(name = "foo")`. Run Bazel. You will get an exception when
the rule `foo` is created (due to a name conflict), which will show you the
full stack trace.
* You can also use [print](/rules/lib/globals/all#print) for debugging. It
displays the message as a `DEBUG` log line during the loading phase. Except
in rare cases, either remove `print` calls, or make them conditional under a
`debugging` parameter that defaults to `False` before submitting the code to
the depot.
## Errors
If you want to throw an error, use the [fail](/rules/lib/globals/all#fail)
function. Explain clearly to the user what went wrong and how to fix their
`BUILD` file. It is not possible to catch an error.
```python theme={null}
def my_macro(name, deps, visibility=None):
if len(deps) < 2:
fail("Expected at least two values in deps")
# ...
```
## Conventions
* All public functions (functions that don't start with underscore) that
instantiate rules must have a `name` argument. This argument should not be
optional (don't give a default value).
* Public functions should use a docstring following
[Python conventions](https://www.python.org/dev/peps/pep-0257/#one-line-docstrings).
* In `BUILD` files, the `name` argument of the macros must be a keyword
argument (not a positional argument).
* The `name` attribute of rules generated by a macro should include the name
argument as a prefix. For example, `macro(name = "foo")` can generate a
`cc_library` `foo` and a genrule `foo_gen`.
* In most cases, optional parameters should have a default value of `None`.
`None` can be passed directly to native rules, which treat it the same as if
you had not passed in any argument. Thus, there is no need to replace it
with `0`, `False`, or `[]` for this purpose. Instead, the macro should defer
to the rules it creates, as their defaults may be complex or may change over
time. Additionally, a parameter that is explicitly set to its default value
looks different than one that is never set (or set to `None`) when accessed
through the query language or build-system internals.
* Macros should have an optional `visibility` argument.
# Macros
Source: https://bazel.build/extending/macros
This page covers the basics of using macros and includes typical use cases,
debugging, and conventions.
A macro is a function called from the `BUILD` file that can instantiate rules.
Macros are mainly used for encapsulation and code reuse of existing rules and
other macros.
Macros come in two flavors: symbolic macros, which are described on this page,
and [legacy macros](/extending/legacy-macros). Where possible, we recommend using
symbolic macros for code clarity.
Symbolic macros offer typed arguments (string to label conversion, relative to
where the macro was called) and the ability to restrict and specify the
visibility of targets created. They are designed to be amenable to lazy
evaluation (which will be added in a future Bazel release). Symbolic macros are
available by default in Bazel 8. Where this document mentions `macros`, it's
referring to **symbolic macros**.
An executable example of symbolic macros can be found in the
[examples repository](https://github.com/bazelbuild/examples/tree/main/macros).
## Usage
Macros are defined in `.bzl` files by calling the
[`macro()`](https://bazel.build/rules/lib/globals/bzl.html#macro) function with
two required parameters: `attrs` and `implementation`.
### Attributes
`attrs` accepts a dictionary of attribute name to [attribute types](https://bazel.build/rules/lib/toplevel/attr#members), which represents
the arguments to the macro. Two common attributes – `name` and `visibility` –
are implicitly added to all macros and are not included in the dictionary passed
to `attrs`.
```starlark theme={null}
# macro/macro.bzl
my_macro = macro(
attrs = {
"deps": attr.label_list(mandatory = True, doc = "The dependencies passed to the inner cc_binary and cc_test targets"),
"create_test": attr.bool(default = False, configurable = False, doc = "If true, creates a test target"),
},
implementation = _my_macro_impl,
)
```
Attribute type declarations accept the
[parameters](https://bazel.build/rules/lib/toplevel/attr#parameters),
`mandatory`, `default`, and `doc`. Most attribute types also accept the
`configurable` parameter, which determines whether the attribute accepts
`select`s. If an attribute is `configurable`, it will parse non-`select` values
as an unconfigurable `select` – `"foo"` will become
`select({"//conditions:default": "foo"})`. Learn more in [selects](#selects).
#### Attribute inheritance
Macros are often intended to wrap a rule (or another macro), and the macro's
author often wants to forward the bulk of the wrapped symbol's attributes
unchanged, using `**kwargs`, to the macro's main target (or main inner macro).
To support this pattern, a macro can *inherit attributes* from a rule or another
macro by passing the [rule](https://bazel.build/rules/lib/builtins/rule) or
[macro symbol](https://bazel.build/rules/lib/builtins/macro) to `macro()`'s
`inherit_attrs` argument. (You can also use the special string `"common"`
instead of a rule or macro symbol to inherit the [common attributes defined for all Starlark build rules](https://bazel.build/reference/be/common-definitions#common-attributes).)
Only public attributes get inherited, and the attributes in the macro's own
`attrs` dictionary override inherited attributes with the same name. You can
also *remove* inherited attributes by using `None` as a value in the `attrs`
dictionary:
```starlark theme={null}
# macro/macro.bzl
my_macro = macro(
inherit_attrs = native.cc_library,
attrs = {
# override native.cc_library's `local_defines` attribute
"local_defines": attr.string_list(default = ["FOO"]),
# do not inherit native.cc_library's `defines` attribute
"defines": None,
},
...
)
```
The default value of non-mandatory inherited attributes is always overridden to
be `None`, regardless of the original attribute definition's default value. If
you need to examine or modify an inherited non-mandatory attribute – for
example, if you want to add a tag to an inherited `tags` attribute – you must
make sure to handle the `None` case in your macro's implementation function:
```starlark theme={null}
# macro/macro.bzl
def _my_macro_impl(name, visibility, tags, **kwargs):
# Append a tag; tags attr is an inherited non-mandatory attribute, and
# therefore is None unless explicitly set by the caller of our macro.
my_tags = (tags or []) + ["another_tag"]
native.cc_library(
...
tags = my_tags,
**kwargs,
)
...
```
### Implementation
`implementation` accepts a function which contains the logic of the macro.
Implementation functions often create targets by calling one or more rules, and
they are usually private (named with a leading underscore). Conventionally,
they are named the same as their macro, but prefixed with `_` and suffixed with
`_impl`.
Unlike rule implementation functions, which take a single argument (`ctx`) that
contains a reference to the attributes, macro implementation functions accept a
parameter for each argument.
```starlark theme={null}
# macro/macro.bzl
def _my_macro_impl(name, visibility, deps, create_test):
cc_library(
name = name + "_cc_lib",
deps = deps,
)
if create_test:
cc_test(
name = name + "_test",
srcs = ["my_test.cc"],
deps = deps,
)
```
If a macro inherits attributes, its implementation function *must* have a
`**kwargs` residual keyword parameter, which can be forwarded to the call that
invokes the inherited rule or submacro. (This helps ensure that your macro won't
be broken if the rule or macro which from which you are inheriting adds a new
attribute.)
### Declaration
Macros are declared by loading and calling their definition in a `BUILD` file.
```starlark theme={null}
# pkg/BUILD
my_macro(
name = "macro_instance",
deps = ["src.cc"] + select(
{
"//config_setting:special": ["special_source.cc"],
"//conditions:default": [],
},
),
create_tests = True,
)
```
This would create targets
`//pkg:macro_instance_cc_lib` and`//pkg:macro_instance_test`.
Just like in rule calls, if an attribute value in a macro call is set to `None`,
that attribute is treated as if it was omitted by the macro's caller. For
example, the following two macro calls are equivalent:
```starlark theme={null}
# pkg/BUILD
my_macro(name = "abc", srcs = ["src.cc"], deps = None)
my_macro(name = "abc", srcs = ["src.cc"])
```
This is generally not useful in `BUILD` files, but is helpful when
programmatically wrapping a macro inside another macro.
## Details
### Naming conventions for targets created
The names of any targets or submacros created by a symbolic macro must
either match the macro's `name` parameter or must be prefixed by `name` followed
by `_` (preferred), `.` or `-`. For example, `my_macro(name = "foo")` may only
create files or targets named `foo`, or prefixed by `foo_`, `foo-` or `foo.`,
for example, `foo_bar`.
Targets or files that violate macro naming convention can be declared, but
cannot be built and cannot be used as dependencies.
Non-macro files and targets within the same package as a macro instance should
*not* have names that conflict with potential macro target names, though this
exclusivity is not enforced. We are in the progress of implementing
[lazy evaluation](#laziness) as a performance improvement for Symbolic macros,
which will be impaired in packages that violate the naming schema.
### Restrictions
Symbolic macros have some additional restrictions compared to legacy macros.
Symbolic macros
* must take a `name` argument and a `visibility` argument
* must have an `implementation` function
* may not return values
* may not mutate their arguments
* may not call `native.existing_rules()` unless they are special `finalizer`
macros
* may not call `native.package()`
* may not call `glob()`
* may not call `native.environment_group()`
* must create targets whose names adhere to the [naming schema](#naming)
* can't refer to input files that weren't declared or passed in as an argument
* can't refer to private targets of their callers (see
[visibility and macros](#visibility) for more details).
### Visibility and macros
The [visibility](/concepts/visibility) system helps protect the implementation
details of both (symbolic) macros and their callers.
By default, targets created in a symbolic macro are visible within the macro
itself, but not necessarily to the macro's caller. The macro can "export" a
target as a public API by forwarding the value of its own `visibility`
attribute, as in `some_rule(..., visibility = visibility)`.
The key ideas of macro visibility are:
1. Visibility is checked based on what macro declared the target, not what
package called the macro.
* In other words, being in the same package does not by itself make one
target visible to another. This protects the macro's internal targets
from becoming dependencies of other macros or top-level targets in the
package.
2. All `visibility` attributes, on both rules and macros, automatically
include the place where the rule or macro was called.
* Thus, a target is unconditionally visible to other targets declared in the
same macro (or the `BUILD` file, if not in a macro).
In practice, this means that when a macro declares a target without setting its
`visibility`, the target defaults to being internal to the macro. (The package's
[default visibility](/reference/be/functions#package.default_visibility) does
not apply within a macro.) Exporting the target means that the target is visible
to whatever the macro's caller specified in the macro's `visibility` attribute,
plus the package of the macro's caller itself, as well as the macro's own code.
Another way of thinking of it is that the visibility of a macro determines who
(aside from the macro itself) can see the macro's exported targets.
```starlark theme={null}
# tool/BUILD
...
some_rule(
name = "some_tool",
visibility = ["//macro:__pkg__"],
)
```
```starlark theme={null}
# macro/macro.bzl
def _impl(name, visibility):
cc_library(
name = name + "_helper",
...
# No visibility passed in. Same as passing `visibility = None` or
# `visibility = ["//visibility:private"]`. Visible to the //macro
# package only.
)
cc_binary(
name = name + "_exported",
deps = [
# Allowed because we're also in //macro. (Targets in any other
# instance of this macro, or any other macro in //macro, can see it
# too.)
name + "_helper",
# Allowed by some_tool's visibility, regardless of what BUILD file
# we're called from.
"//tool:some_tool",
],
...
visibility = visibility,
)
my_macro = macro(implementation = _impl, ...)
```
```starlark theme={null}
# pkg/BUILD
load("//macro:macro.bzl", "my_macro")
...
my_macro(
name = "foo",
...
)
some_rule(
...
deps = [
# Allowed, its visibility is ["//pkg:__pkg__", "//macro:__pkg__"].
":foo_exported",
# Disallowed, its visibility is ["//macro:__pkg__"] and
# we are not in //macro.
":foo_helper",
]
)
```
If `my_macro` were called with `visibility = ["//other_pkg:__pkg__"]`, or if
the `//pkg` package had set its `default_visibility` to that value, then
`//pkg:foo_exported` could also be used within `//other_pkg/BUILD` or within a
macro defined in `//other_pkg:defs.bzl`, but `//pkg:foo_helper` would remain
protected.
A macro can declare that a target is visible to a friend package by passing
`visibility = ["//some_friend:__pkg__"]` (for an internal target) or
`visibility = visibility + ["//some_friend:__pkg__"]` (for an exported one).
Note that it is an antipattern for a macro to declare a target with public
visibility (`visibility = ["//visibility:public"]`). This is because it makes
the target unconditionally visible to every package, even if the caller
specified a more restricted visibility.
All visibility checking is done with respect to the innermost currently running
symbolic macro. However, there is a visibility delegation mechanism: If a macro
passes a label as an attribute value to an inner macro, any usages of the label
in the inner macro are checked with respect to the outer macro. See the
[visibility page](/concepts/visibility#symbolic-macros) for more details.
Remember that legacy macros are entirely transparent to the visibility system,
and behave as though their location is whatever BUILD file or symbolic macro
they were called from.
#### Finalizers and visibility
Targets declared in a rule finalizer, in addition to seeing targets following
the usual symbolic macro visibility rules, can *also* see all targets which are
visible to the finalizer target's package.
This means that if you migrate a `native.existing_rules()`-based legacy macro to
a finalizer, the targets declared by the finalizer will still be able to see
their old dependencies.
However, note that it's possible to declare a target in a symbolic macro such
that a finalizer's targets cannot see it under the visibility system – even
though the finalizer can *introspect* its attributes using
`native.existing_rules()`.
### Selects
If an attribute is `configurable` (the default) and its value is not `None`,
then the macro implementation function will see the attribute value as wrapped
in a trivial `select`. This makes it easier for the macro author to catch bugs
where they did not anticipate that the attribute value could be a `select`.
For example, consider the following macro:
```starlark theme={null}
my_macro = macro(
attrs = {"deps": attr.label_list()}, # configurable unless specified otherwise
implementation = _my_macro_impl,
)
```
If `my_macro` is invoked with `deps = ["//a"]`, that will cause `_my_macro_impl`
to be invoked with its `deps` parameter set to `select({"//conditions:default": ["//a"]})`. If this causes the implementation function to fail (say, because the
code tried to index into the value as in `deps[0]`, which is not allowed for
`select`s), the macro author can then make a choice: either they can rewrite
their macro to only use operations compatible with `select`, or they can mark
the attribute as nonconfigurable (`attr.label_list(configurable = False)`). The
latter ensures that users are not permitted to pass a `select` value in.
Rule targets reverse this transformation, and store trivial `select`s as their
unconditional values; in the above example, if `_my_macro_impl` declares a rule
target `my_rule(..., deps = deps)`, that rule target's `deps` will be stored as
`["//a"]`. This ensures that `select`-wrapping does not cause trivial `select`
values to be stored in all targets instantiated by macros.
If the value of a configurable attribute is `None`, it does not get wrapped in a
`select`. This ensures that tests like `my_attr == None` still work, and that
when the attribute is forwarded to a rule with a computed default, the rule
behaves properly (that is, as if the attribute were not passed in at all). It is
not always possible for an attribute to take on a `None` value, but it can
happen for the `attr.label()` type, and for any inherited non-mandatory
attribute.
## Finalizers
A rule finalizer is a special symbolic macro which – regardless of its lexical
position in a BUILD file – is evaluated in the final stage of loading a package,
after all non-finalizer targets have been defined. Unlike ordinary symbolic
macros, a finalizer can call `native.existing_rules()`, where it behaves
slightly differently than in legacy macros: it only returns the set of
non-finalizer rule targets. The finalizer may assert on the state of that set or
define new targets.
To declare a finalizer, call `macro()` with `finalizer = True`:
```starlark theme={null}
def _my_finalizer_impl(name, visibility, tags_filter):
for r in native.existing_rules().values():
for tag in r.get("tags", []):
if tag in tags_filter:
my_test(
name = name + "_" + r["name"] + "_finalizer_test",
deps = [r["name"]],
data = r["srcs"],
...
)
continue
my_finalizer = macro(
attrs = {"tags_filter": attr.string_list(configurable = False)},
implementation = _impl,
finalizer = True,
)
```
## Laziness
IMPORTANT: We are in the process of implementing lazy macro expansion and
evaluation. This feature is not available yet.
Currently, all macros are evaluated as soon as the BUILD file is loaded, which
can negatively impact performance for targets in packages that also have costly
unrelated macros. In the future, non-finalizer symbolic macros will only be
evaluated if they're required for the build. The prefix naming schema helps
Bazel determine which macro to expand given a requested target.
## Migration troubleshooting
Here are some common migration headaches and how to fix them.
* Legacy macro calls `glob()`
Move the `glob()` call to your BUILD file (or to a legacy macro called from the
BUILD file), and pass the `glob()` value to the symbolic macro using a
label-list attribute:
```starlark theme={null}
# BUILD file
my_macro(
...,
deps = glob(...),
)
```
* Legacy macro has a parameter that isn't a valid starlark `attr` type.
Pull as much logic as possible into a nested symbolic macro, but keep the
top level macro a legacy macro.
* Legacy macro calls a rule that creates a target that breaks the naming schema
That's okay, just don't depend on the "offending" target. The naming check will
be quietly ignored.
# Rules
Source: https://bazel.build/extending/rules
A **rule** defines a series of [**actions**](#actions) that Bazel performs on
inputs to produce a set of outputs, which are referenced in
[**providers**](#providers) returned by the rule's
[**implementation function**](#implementation_function). For example, a C++
binary rule might:
1. Take a set of `.cpp` source files (inputs).
2. Run `g++` on the source files (action).
3. Return the `DefaultInfo` provider with the executable output and other files
to make available at runtime.
4. Return the `CcInfo` provider with C++-specific information gathered from the
target and its dependencies.
From Bazel's perspective, `g++` and the standard C++ libraries are also inputs
to this rule. As a rule writer, you must consider not only the user-provided
inputs to a rule, but also all of the tools and libraries required to execute
the actions.
Before creating or modifying any rule, ensure you are familiar with Bazel's
[build phases](/extending/concepts). It is important to understand the three
phases of a build (loading, analysis, and execution). It is also useful to
learn about [macros](/extending/macros) to understand the difference between rules and
macros. To get started, first review the [Rules Tutorial](/rules/rules-tutorial).
Then, use this page as a reference.
A few rules are built into Bazel itself. These *native rules*, such as
`genrule` and `filegroup`, provide some core support.
By defining your own rules, you can add support for languages and tools
that Bazel doesn't support natively.
Bazel provides an extensibility model for writing rules using the
[Starlark](/rules/language) language. These rules are written in `.bzl` files, which
can be loaded directly from `BUILD` files.
When defining your own rule, you get to decide what attributes it supports and
how it generates its outputs.
The rule's `implementation` function defines its exact behavior during the
[analysis phase](/extending/concepts#evaluation-model). This function doesn't run any
external commands. Rather, it registers [actions](#actions) that will be used
later during the execution phase to build the rule's outputs, if they are
needed.
## Rule creation
In a `.bzl` file, use the [rule](/rules/lib/globals/bzl#rule) function to define a new
rule, and store the result in a global variable. The call to `rule` specifies
[attributes](#attributes) and an
[implementation function](#implementation_function):
```python theme={null}
example_library = rule(
implementation = _example_library_impl,
attrs = {
"deps": attr.label_list(),
...
},
)
```
This defines a [rule kind](/query/language#kind) named `example_library`.
The call to `rule` also must specify if the rule creates an
[executable](#executable-rules) output (with `executable = True`), or specifically
a test executable (with `test = True`). If the latter, the rule is a *test rule*,
and the name of the rule must end in `_test`.
## Target instantiation
Rules can be [loaded](/concepts/build-files#load) and called in `BUILD` files:
```python theme={null}
load('//some/pkg:rules.bzl', 'example_library')
example_library(
name = "example_target",
deps = [":another_target"],
...
)
```
Each call to a build rule returns no value, but has the side effect of defining
a target. This is called *instantiating* the rule. This specifies a name for the
new target and values for the target's [attributes](#attributes).
Rules can also be called from Starlark functions and loaded in `.bzl` files.
Starlark functions that call rules are called [Starlark macros](/extending/macros).
Starlark macros must ultimately be called from `BUILD` files, and can only be
called during the [loading phase](/extending/concepts#evaluation-model), when `BUILD`
files are evaluated to instantiate targets.
## Attributes
An *attribute* is a rule argument. Attributes can provide specific values to a
target's [implementation](#implementation_function), or they can refer to other
targets, creating a graph of dependencies.
Rule-specific attributes, such as `srcs` or `deps`, are defined by passing a map
from attribute names to schemas (created using the [`attr`](/rules/lib/toplevel/attr)
module) to the `attrs` parameter of `rule`.
[Common attributes](/reference/be/common-definitions#common-attributes), such as
`name` and `visibility`, are implicitly added to all rules. Additional
attributes are implicitly added to
[executable and test rules](#executable-rules) specifically. Attributes which
are implicitly added to a rule can't be included in the dictionary passed to
`attrs`.
### Dependency attributes
Rules that process source code usually define the following attributes to handle
various [types of dependencies](/concepts/dependencies#types_of_dependencies):
* `srcs` specifies source files processed by a target's actions. Often, the
attribute schema specifies which file extensions are expected for the sort
of source file the rule processes. Rules for languages with header files
generally specify a separate `hdrs` attribute for headers processed by a
target and its consumers.
* `deps` specifies code dependencies for a target. The attribute schema should
specify which [providers](#providers) those dependencies must provide. (For
example, `cc_library` provides `CcInfo`.)
* `data` specifies files to be made available at runtime to any executable
which depends on a target. That should allow arbitrary files to be
specified.
```python theme={null}
example_library = rule(
implementation = _example_library_impl,
attrs = {
"srcs": attr.label_list(allow_files = [".example"]),
"hdrs": attr.label_list(allow_files = [".header"]),
"deps": attr.label_list(providers = [ExampleInfo]),
"data": attr.label_list(allow_files = True),
...
},
)
```
These are examples of *dependency attributes*. Any attribute that specifies
an input label (those defined with
[`attr.label_list`](/rules/lib/toplevel/attr#label_list),
[`attr.label`](/rules/lib/toplevel/attr#label), or
[`attr.label_keyed_string_dict`](/rules/lib/toplevel/attr#label_keyed_string_dict))
specifies dependencies of a certain type
between a target and the targets whose labels (or the corresponding
[`Label`](/rules/lib/builtins/Label) objects) are listed in that attribute when the target
is defined. The repository, and possibly the path, for these labels is resolved
relative to the defined target.
```python theme={null}
example_library(
name = "my_target",
deps = [":other_target"],
)
example_library(
name = "other_target",
...
)
```
In this example, `other_target` is a dependency of `my_target`, and therefore
`other_target` is analyzed first. It is an error if there is a cycle in the
dependency graph of targets.
### Private attributes and implicit dependencies
A dependency attribute with a default value creates an *implicit dependency*. It
is implicit because it's a part of the target graph that the user doesn't
specify it in a `BUILD` file. Implicit dependencies are useful for hard-coding a
relationship between a rule and a *tool* (a build-time dependency, such as a
compiler), since most of the time a user is not interested in specifying what
tool the rule uses. Inside the rule's implementation function, this is treated
the same as other dependencies.
If you want to provide an implicit dependency without allowing the user to
override that value, you can make the attribute *private* by giving it a name
that begins with an underscore (`_`). Private attributes must have default
values. It generally only makes sense to use private attributes for implicit
dependencies.
```python theme={null}
example_library = rule(
implementation = _example_library_impl,
attrs = {
...
"_compiler": attr.label(
default = Label("//tools:example_compiler"),
allow_single_file = True,
executable = True,
cfg = "exec",
),
},
)
```
In this example, every target of type `example_library` has an implicit
dependency on the compiler `//tools:example_compiler`. This allows
`example_library`'s implementation function to generate actions that invoke the
compiler, even though the user did not pass its label as an input. Since
`_compiler` is a private attribute, it follows that `ctx.attr._compiler`
will always point to `//tools:example_compiler` in all targets of this rule
type. Alternatively, you can name the attribute `compiler` without the
underscore and keep the default value. This allows users to substitute a
different compiler if necessary, but it requires no awareness of the compiler's
label.
Implicit dependencies are generally used for tools that reside in the same
repository as the rule implementation. If the tool comes from the
[execution platform](/extending/platforms) or a different repository instead, the
rule should obtain that tool from a [toolchain](/extending/toolchains).
### Output attributes
*Output attributes*, such as [`attr.output`](/rules/lib/toplevel/attr#output) and
[`attr.output_list`](/rules/lib/toplevel/attr#output_list), declare an output file that the
target generates. These differ from dependency attributes in two ways:
* They define output file targets instead of referring to targets defined
elsewhere.
* The output file targets depend on the instantiated rule target, instead of
the other way around.
Typically, output attributes are only used when a rule needs to create outputs
with user-defined names which can't be based on the target name. If a rule has
one output attribute, it is typically named `out` or `outs`.
Output attributes are the preferred way of creating *predeclared outputs*, which
can be specifically depended upon or
[requested at the command line](#requesting_output_files).
## Implementation function
Every rule requires an `implementation` function. These functions are executed
strictly in the [analysis phase](/extending/concepts#evaluation-model) and transform the
graph of targets generated in the loading phase into a graph of
[actions](#actions) to be performed during the execution phase. As such,
implementation functions can't actually read or write files.
Rule implementation functions are usually private (named with a leading
underscore). Conventionally, they are named the same as their rule, but suffixed
with `_impl`.
Implementation functions take exactly one parameter: a
[rule context](/rules/lib/builtins/ctx), conventionally named `ctx`. They return a list of
[providers](#providers).
### Targets
Dependencies are represented at analysis time as [`Target`](/rules/lib/builtins/Target)
objects. These objects contain the [providers](#providers) generated when the
target's implementation function was executed.
[`ctx.attr`](/rules/lib/builtins/ctx#attr) has fields corresponding to the names of each
dependency attribute, containing `Target` objects representing each direct
dependency using that attribute. For `label_list` attributes, this is a list of
`Targets`. For `label` attributes, this is a single `Target` or `None`.
A list of provider objects are returned by a target's implementation function:
```python theme={null}
return [ExampleInfo(headers = depset(...))]
```
Those can be accessed using index notation (`[]`), with the type of provider as
a key. These can be [custom providers](#custom_providers) defined in Starlark or
[providers for native rules](/rules/lib/providers) available as Starlark
global variables.
For example, if a rule takes header files using a `hdrs` attribute and provides
them to the compilation actions of the target and its consumers, it could
collect them like so:
```python theme={null}
def _example_library_impl(ctx):
...
transitive_headers = [hdr[ExampleInfo].headers for hdr in ctx.attr.hdrs]
```
There's a legacy struct style, which is strongly discouraged and rules should be
[migrated away from it](#migrating_from_legacy_providers).
### Files
Files are represented by [`File`](/rules/lib/builtins/File) objects. Since Bazel doesn't
perform file I/O during the analysis phase, these objects can't be used to
directly read or write file content. Rather, they are passed to action-emitting
functions (see [`ctx.actions`](/rules/lib/builtins/actions)) to construct pieces of the
action graph.
A `File` can either be a source file or a generated file. Each generated file
must be an output of exactly one action. Source files can't be the output of
any action.
For each dependency attribute, the corresponding field of
[`ctx.files`](/rules/lib/builtins/ctx#files) contains a list of the default outputs of all
dependencies using that attribute:
```python theme={null}
def _example_library_impl(ctx):
...
headers = depset(ctx.files.hdrs, transitive = transitive_headers)
srcs = ctx.files.srcs
...
```
[`ctx.file`](/rules/lib/builtins/ctx#file) contains a single `File` or `None` for
dependency attributes whose specs set `allow_single_file = True`.
[`ctx.executable`](/rules/lib/builtins/ctx#executable) behaves the same as `ctx.file`, but only
contains fields for dependency attributes whose specs set `executable = True`.
### Declaring outputs
During the analysis phase, a rule's implementation function can create outputs.
Since all labels have to be known during the loading phase, these additional
outputs have no labels. `File` objects for outputs can be created using
[`ctx.actions.declare_file`](/rules/lib/builtins/actions#declare_file) and
[`ctx.actions.declare_directory`](/rules/lib/builtins/actions#declare_directory).
Often, the names of outputs are based on the target's name,
[`ctx.label.name`](/rules/lib/builtins/ctx#label):
```python theme={null}
def _example_library_impl(ctx):
...
output_file = ctx.actions.declare_file(ctx.label.name + ".output")
...
```
For *predeclared outputs*, like those created for
[output attributes](#output_attributes), `File` objects instead can be retrieved
from the corresponding fields of [`ctx.outputs`](/rules/lib/builtins/ctx#outputs).
### Actions
An action describes how to generate a set of outputs from a set of inputs, for
example "run gcc on hello.c and get hello.o". When an action is created, Bazel
doesn't run the command immediately. It registers it in a graph of dependencies,
because an action can depend on the output of another action. For example, in C,
the linker must be called after the compiler.
General-purpose functions that create actions are defined in
[`ctx.actions`](/rules/lib/builtins/actions):
* [`ctx.actions.run`](/rules/lib/builtins/actions#run), to run an executable.
* [`ctx.actions.run_shell`](/rules/lib/builtins/actions#run_shell), to run a shell
command.
* [`ctx.actions.write`](/rules/lib/builtins/actions#write), to write a string to a file.
* [`ctx.actions.expand_template`](/rules/lib/builtins/actions#expand_template), to
generate a file from a template.
[`ctx.actions.args`](/rules/lib/builtins/actions#args) can be used to efficiently
accumulate the arguments for actions. It avoids flattening depsets until
execution time:
```python theme={null}
def _example_library_impl(ctx):
...
transitive_headers = [dep[ExampleInfo].headers for dep in ctx.attr.deps]
headers = depset(ctx.files.hdrs, transitive = transitive_headers)
srcs = ctx.files.srcs
inputs = depset(srcs, transitive = [headers])
output_file = ctx.actions.declare_file(ctx.label.name + ".output")
args = ctx.actions.args()
args.add_joined("-h", headers, join_with = ",")
args.add_joined("-s", srcs, join_with = ",")
args.add("-o", output_file)
ctx.actions.run(
mnemonic = "ExampleCompile",
executable = ctx.executable._compiler,
arguments = [args],
inputs = inputs,
outputs = [output_file],
)
...
```
Actions take a list or depset of input files and generate a (non-empty) list of
output files. The set of input and output files must be known during the
[analysis phase](/extending/concepts#evaluation-model). It might depend on the value of
attributes, including providers from dependencies, but it can't depend on the
result of the execution. For example, if your action runs the unzip command, you
must specify which files you expect to be inflated (before running unzip).
Actions which create a variable number of files internally can wrap those in a
single file (such as a zip, tar, or other archive format).
Actions must list all of their inputs. Listing inputs that are not used is
permitted, but inefficient.
Actions must create all of their outputs. They may write other files, but
anything not in outputs won't be available to consumers. All declared outputs
must be written by some action.
Actions are comparable to pure functions: They should depend only on the
provided inputs, and avoid accessing computer information, username, clock,
network, or I/O devices (except for reading inputs and writing outputs). This is
important because the output will be cached and reused.
Dependencies are resolved by Bazel, which decides which actions to
execute. It is an error if there is a cycle in the dependency graph. Creating
an action doesn't guarantee that it will be executed, that depends on whether
its outputs are needed for the build.
### Providers
Providers are pieces of information that a rule exposes to other rules that
depend on it. This data can include output files, libraries, parameters to pass
on a tool's command line, or anything else a target's consumers should know
about.
Since a rule's implementation function can only read providers from the
instantiated target's immediate dependencies, rules need to forward any
information from a target's dependencies that needs to be known by a target's
consumers, generally by accumulating that into a [`depset`](/rules/lib/builtins/depset).
A target's providers are specified by a list of provider objects returned by
the implementation function.
Old implementation functions can also be written in a legacy style where the
implementation function returns a [`struct`](/rules/lib/builtins/struct) instead of list of
provider objects. This style is strongly discouraged and rules should be
[migrated away from it](#migrating_from_legacy_providers).
#### Default outputs
A target's *default outputs* are the outputs that are requested by default when
the target is requested for build at the command line. For example, a
`java_library` target `//pkg:foo` has `foo.jar` as a default output, so that
will be built by the command `bazel build //pkg:foo`.
Default outputs are specified by the `files` parameter of
[`DefaultInfo`](/rules/lib/providers/DefaultInfo):
```python theme={null}
def _example_library_impl(ctx):
...
return [
DefaultInfo(files = depset([output_file]), ...),
...
]
```
If `DefaultInfo` is not returned by a rule implementation or the `files`
parameter is not specified, `DefaultInfo.files` defaults to all
*predeclared outputs* (generally, those created by [output attributes](#output_attributes)).
Rules that perform actions should provide default outputs, even if those outputs
are not expected to be directly used. Actions that are not in the graph of the
requested outputs are pruned. If an output is only used by a target's consumers,
those actions won't be performed when the target is built in isolation. This
makes debugging more difficult because rebuilding just the failing target won't
reproduce the failure.
#### Runfiles
Runfiles are a set of files used by a target at runtime (as opposed to build
time). During the [execution phase](/extending/concepts#evaluation-model), Bazel creates
a directory tree containing symlinks pointing to the runfiles. This stages the
environment for the binary so it can access the runfiles during runtime.
Runfiles can be added manually during rule creation.
[`runfiles`](/rules/lib/builtins/runfiles) objects can be created by the `runfiles` method
on the rule context, [`ctx.runfiles`](/rules/lib/builtins/ctx#runfiles) and passed to the
`runfiles` parameter on `DefaultInfo`. The executable output of
[executable rules](#executable-rules) is implicitly added to the runfiles.
Some rules specify attributes, generally named
[`data`](/reference/be/common-definitions#common.data), whose outputs are added to
a targets' runfiles. Runfiles should also be merged in from `data`, as well as
from any attributes which might provide code for eventual execution, generally
`srcs` (which might contain `filegroup` targets with associated `data`) and
`deps`.
```python theme={null}
def _example_library_impl(ctx):
...
runfiles = ctx.runfiles(files = ctx.files.data)
transitive_runfiles = []
for runfiles_attr in (
ctx.attr.srcs,
ctx.attr.hdrs,
ctx.attr.deps,
ctx.attr.data,
):
for target in runfiles_attr:
transitive_runfiles.append(target[DefaultInfo].default_runfiles)
runfiles = runfiles.merge_all(transitive_runfiles)
return [
DefaultInfo(..., runfiles = runfiles),
...
]
```
#### Custom providers
Providers can be defined using the [`provider`](/rules/lib/globals/bzl#provider)
function to convey rule-specific information:
```python theme={null}
ExampleInfo = provider(
"Info needed to compile/link Example code.",
fields = {
"headers": "depset of header Files from transitive dependencies.",
"files_to_link": "depset of Files from compilation.",
},
)
```
The `fields` parameter to `provider` is optional, but strongly recommended.
Specifying `fields` creates a *schemaful provider*, which allows Bazel to store
provider instances more compactly.
Rule implementation functions can then construct and return provider instances:
```python theme={null}
def _example_library_impl(ctx):
...
return [
...
ExampleInfo(
headers = headers,
files_to_link = depset(
[output_file],
transitive = [
dep[ExampleInfo].files_to_link for dep in ctx.attr.deps
],
),
)
]
```
##### Custom initialization of providers
It's possible to guard the instantiation of a provider with custom
preprocessing and validation logic. This can be used to ensure that all
provider instances satisfy certain invariants, or to give users a cleaner API for
obtaining an instance.
This is done by passing an `init` callback to the
[`provider`](/rules/lib/globals/bzl#provider) function. If this callback is given, the
return type of `provider()` changes to be a tuple of two values: the provider
symbol that is the ordinary return value when `init` is not used, and a "raw
constructor".
In this case, when the provider symbol is called, instead of directly returning
a new instance, it will forward the arguments along to the `init` callback. The
callback's return value must be a dict mapping field names (strings) to values;
this is used to initialize the fields of the new instance. Note that the
callback may have any signature, and if the arguments don't match the signature
an error is reported as if the callback were invoked directly.
The raw constructor, by contrast, will bypass the `init` callback.
The following example uses `init` to preprocess and validate its arguments:
```python theme={null}
# //pkg:exampleinfo.bzl
_core_headers = [...] # private constant representing standard library files
# Keyword-only arguments are preferred.
def _exampleinfo_init(*, files_to_link, headers = None, allow_empty_files_to_link = False):
if not files_to_link and not allow_empty_files_to_link:
fail("files_to_link may not be empty")
all_headers = depset(_core_headers, transitive = headers)
return {"files_to_link": files_to_link, "headers": all_headers}
ExampleInfo, _new_exampleinfo = provider(
fields = ["files_to_link", "headers"],
init = _exampleinfo_init,
)
```
A rule implementation may then instantiate the provider as follows:
```python theme={null}
ExampleInfo(
files_to_link = my_files_to_link, # may not be empty
headers = my_headers, # will automatically include the core headers
)
```
The raw constructor can be used to define alternative public factory functions
that don't go through the `init` logic. For example, exampleinfo.bzl
could define:
```python theme={null}
def make_barebones_exampleinfo(headers):
"""Returns an ExampleInfo with no files_to_link and only the specified headers."""
return _new_exampleinfo(files_to_link = depset(), headers = all_headers)
```
Typically, the raw constructor is bound to a variable whose name begins with an
underscore (`_new_exampleinfo` above), so that user code can't load it and
generate arbitrary provider instances.
Another use for `init` is to prevent the user from calling the provider
symbol altogether, and force them to use a factory function instead:
```python theme={null}
def _exampleinfo_init_banned(*args, **kwargs):
fail("Do not call ExampleInfo(). Use make_exampleinfo() instead.")
ExampleInfo, _new_exampleinfo = provider(
...
init = _exampleinfo_init_banned)
def make_exampleinfo(...):
...
return _new_exampleinfo(...)
```
## Executable rules and test rules
Executable rules define targets that can be invoked by a `bazel run` command.
Test rules are a special kind of executable rule whose targets can also be
invoked by a `bazel test` command. Executable and test rules are created by
setting the respective [`executable`](/rules/lib/globals/bzl#rule.executable) or
[`test`](/rules/lib/globals/bzl#rule.test) argument to `True` in the call to `rule`:
```python theme={null}
example_binary = rule(
implementation = _example_binary_impl,
executable = True,
...
)
example_test = rule(
implementation = _example_binary_impl,
test = True,
...
)
```
Test rules must have names that end in `_test`. (Test *target* names also often
end in `_test` by convention, but this is not required.) Non-test rules must not
have this suffix.
Both kinds of rules must produce an executable output file (which may or may not
be predeclared) that will be invoked by the `run` or `test` commands. To tell
Bazel which of a rule's outputs to use as this executable, pass it as the
`executable` argument of a returned [`DefaultInfo`](/rules/lib/providers/DefaultInfo)
provider. That `executable` is added to the default outputs of the rule (so you
don't need to pass that to both `executable` and `files`). It's also implicitly
added to the [runfiles](#runfiles):
```python theme={null}
def _example_binary_impl(ctx):
executable = ctx.actions.declare_file(ctx.label.name)
...
return [
DefaultInfo(executable = executable, ...),
...
]
```
The action that generates this file must set the executable bit on the file. For
a [`ctx.actions.run`](/rules/lib/builtins/actions#run) or
[`ctx.actions.run_shell`](/rules/lib/builtins/actions#run_shell) action this should be done
by the underlying tool that is invoked by the action. For a
[`ctx.actions.write`](/rules/lib/builtins/actions#write) action, pass `is_executable = True`.
As [legacy behavior](#deprecated_predeclared_outputs), executable rules have a
special `ctx.outputs.executable` predeclared output. This file serves as the
default executable if you don't specify one using `DefaultInfo`; it must not be
used otherwise. This output mechanism is deprecated because it doesn't support
customizing the executable file's name at analysis time.
See examples of an
[executable rule](https://github.com/bazelbuild/examples/blob/main/rules/executable/fortune.bzl)
and a
[test rule](https://github.com/bazelbuild/examples/blob/main/rules/test_rule/line_length.bzl).
[Executable rules](/reference/be/common-definitions#common-attributes-binaries) and
[test rules](/reference/be/common-definitions#common-attributes-tests) have additional
attributes implicitly defined, in addition to those added for
[all rules](/reference/be/common-definitions#common-attributes). The defaults of
implicitly-added attributes can't be changed, though this can be worked around
by wrapping a private rule in a [Starlark macro](/extending/macros) which alters the
default:
```python theme={null}
def example_test(size = "small", **kwargs):
_example_test(size = size, **kwargs)
_example_test = rule(
...
)
```
### Runfiles location
When an executable target is run with `bazel run` (or `test`), the root of the
runfiles directory is adjacent to the executable. The paths relate as follows:
```python theme={null}
# Given launcher_path and runfile_file:
runfiles_root = launcher_path.path + ".runfiles"
workspace_name = ctx.workspace_name
runfile_path = runfile_file.short_path
execution_root_relative_path = "%s/%s/%s" % (
runfiles_root, workspace_name, runfile_path)
```
The path to a `File` under the runfiles directory corresponds to
[`File.short_path`](/rules/lib/builtins/File#short_path).
The binary executed directly by `bazel` is adjacent to the root of the
`runfiles` directory. However, binaries called *from* the runfiles can't make
the same assumption. To mitigate this, each binary should provide a way to
accept its runfiles root as a parameter using an environment, or command line
argument or flag. This allows binaries to pass the correct canonical runfiles root
to the binaries it calls. If that's not set, a binary can guess that it was the
first binary called and look for an adjacent runfiles directory.
## Advanced topics
### Requesting output files
A single target can have several output files. When a `bazel build` command is
run, some of the outputs of the targets given to the command are considered to
be *requested*. Bazel only builds these requested files and the files that they
directly or indirectly depend on. (In terms of the action graph, Bazel only
executes the actions that are reachable as transitive dependencies of the
requested files.)
In addition to [default outputs](#default_outputs), any *predeclared output* can
be explicitly requested on the command line. Rules can specify predeclared
outputs using [output attributes](#output_attributes). In that case, the user
explicitly chooses labels for outputs when they instantiate the rule. To obtain
[`File`](/rules/lib/builtins/File) objects for output attributes, use the corresponding
attribute of [`ctx.outputs`](/rules/lib/builtins/ctx#outputs). Rules can
[implicitly define predeclared outputs](#deprecated_predeclared_outputs) based
on the target name as well, but this feature is deprecated.
In addition to default outputs, there are *output groups*, which are collections
of output files that may be requested together. These can be requested with
[`--output_groups`](/reference/command-line-reference#flag--output_groups). For
example, if a target `//pkg:mytarget` is of a rule type that has a `debug_files`
output group, these files can be built by running `bazel build //pkg:mytarget --output_groups=debug_files`. Since non-predeclared outputs don't have labels,
they can only be requested by appearing in the default outputs or an output
group.
Output groups can be specified with the
[`OutputGroupInfo`](/rules/lib/providers/OutputGroupInfo) provider. Note that unlike many
built-in providers, `OutputGroupInfo` can take parameters with arbitrary names
to define output groups with that name:
```python theme={null}
def _example_library_impl(ctx):
...
debug_file = ctx.actions.declare_file(name + ".pdb")
...
return [
DefaultInfo(files = depset([output_file]), ...),
OutputGroupInfo(
debug_files = depset([debug_file]),
all_files = depset([output_file, debug_file]),
),
...
]
```
Also unlike most providers, `OutputGroupInfo` can be returned by both an
[aspect](/extending/aspects) and the rule target to which that aspect is applied, as
long as they don't define the same output groups. In that case, the resulting
providers are merged.
Note that `OutputGroupInfo` generally shouldn't be used to convey specific sorts
of files from a target to the actions of its consumers. Define
[rule-specific providers](#custom_providers) for that instead.
### Configurations
Imagine that you want to build a C++ binary for a different architecture. The
build can be complex and involve multiple steps. Some of the intermediate
binaries, like compilers and code generators, have to run on
[the execution platform](/extending/platforms#overview) (which could be your host,
or a remote executor). Some binaries like the final output must be built for the
target architecture.
For this reason, Bazel has a concept of "configurations" and transitions. The
topmost targets (the ones requested on the command line) are built-in the
"target" configuration, while tools that should run on the execution platform
are built-in an "exec" configuration. Rules may generate different actions based
on the configuration, for instance to change the cpu architecture that is passed
to the compiler. In some cases, the same library may be needed for different
configurations. If this happens, it will be analyzed and potentially built
multiple times.
By default, Bazel builds a target's dependencies in the same configuration as
the target itself, in other words without transitions. When a dependency is a
tool that's needed to help build the target, the corresponding attribute should
specify a transition to an exec configuration. This causes the tool and all its
dependencies to build for the execution platform.
For each dependency attribute, you can use `cfg` to decide if dependencies
should build in the same configuration or transition to an exec configuration.
If a dependency attribute has the flag `executable = True`, `cfg` must be set
explicitly. This is to guard against accidentally building a tool for the wrong
configuration.
[See example](https://github.com/bazelbuild/examples/blob/main/rules/actions_run/execute.bzl)
In general, sources, dependent libraries, and executables that will be needed at
runtime can use the same configuration.
Tools that are executed as part of the build (such as compilers or code generators)
should be built for an exec configuration. In this case, specify `cfg = "exec"` in
the attribute.
Otherwise, executables that are used at runtime (e.g. as part of a test) should
be built for the target configuration. In this case, specify `cfg = "target"` in
the attribute.
`cfg = "target"` doesn't actually do anything: it's purely a convenience value to
help rule designers be explicit about their intentions. When `executable = False`,
which means `cfg` is optional, only set this when it truly helps readability.
You can also use `cfg = my_transition` to use
[user-defined transitions](/extending/config#user-defined-transitions), which allow
rule authors a great deal of flexibility in changing configurations, with the
drawback of
[making the build graph larger and less comprehensible](/extending/config#memory-and-performance-considerations).
**Note**: Historically, Bazel didn't have the concept of execution platforms,
and instead all build actions were considered to run on the host machine. Bazel
versions before 6.0 created a distinct "host" configuration to represent this.
If you see references to "host" in code or old documentation, that's what this
refers to. We recommend using Bazel 6.0 or newer to avoid this extra conceptual
overhead.
### Configuration fragments
Rules may access
[configuration fragments](/rules/lib/fragments) such as
`cpp` and `java`. However, all required fragments must be declared in
order to avoid access errors:
```python theme={null}
def _impl(ctx):
# Using ctx.fragments.cpp leads to an error since it was not declared.
x = ctx.fragments.java
...
my_rule = rule(
implementation = _impl,
fragments = ["java"], # Required fragments of the target configuration
...
)
```
### Runfiles symlinks
Normally, the relative path of a file in the runfiles tree is the same as the
relative path of that file in the source tree or generated output tree. If these
need to be different for some reason, you can specify the `root_symlinks` or
`symlinks` arguments. The `root_symlinks` is a dictionary mapping paths to
files, where the paths are relative to the root of the runfiles directory. The
`symlinks` dictionary is the same, but paths are implicitly prefixed with the
name of the main workspace (*not* the name of the repository containing the
current target).
```python theme={null}
...
runfiles = ctx.runfiles(
root_symlinks = {"some/path/here.foo": ctx.file.some_data_file2}
symlinks = {"some/path/here.bar": ctx.file.some_data_file3}
)
# Creates something like:
# sometarget.runfiles/
# some/
# path/
# here.foo -> some_data_file2
# /
# some/
# path/
# here.bar -> some_data_file3
```
If `symlinks` or `root_symlinks` is used, be careful not to map two different
files to the same path in the runfiles tree. This will cause the build to fail
with an error describing the conflict. To fix, you will need to modify your
`ctx.runfiles` arguments to remove the collision. This checking will be done for
any targets using your rule, as well as targets of any kind that depend on those
targets. This is especially risky if your tool is likely to be used transitively
by another tool; symlink names must be unique across the runfiles of a tool and
all of its dependencies.
### Code coverage
When the [`coverage`](/reference/command-line-reference#coverage) command is run,
the build may need to add coverage instrumentation for certain targets. The
build also gathers the list of source files that are instrumented. The subset of
targets that are considered is controlled by the flag
[`--instrumentation_filter`](/reference/command-line-reference#flag--instrumentation_filter).
Test targets are excluded, unless
[`--instrument_test_targets`](/reference/command-line-reference#flag--instrument_test_targets)
is specified.
If a rule implementation adds coverage instrumentation at build time, it needs
to account for that in its implementation function.
[ctx.coverage\_instrumented](/rules/lib/builtins/ctx#coverage_instrumented) returns
`True` in coverage mode if a target's sources should be instrumented:
```python theme={null}
# Are this rule's sources instrumented?
if ctx.coverage_instrumented():
# Do something to turn on coverage for this compile action
```
Logic that always needs to be on in coverage mode (whether a target's sources
specifically are instrumented or not) can be conditioned on
[ctx.configuration.coverage\_enabled](/rules/lib/builtins/configuration#coverage_enabled).
If the rule directly includes sources from its dependencies before compilation
(such as header files), it may also need to turn on compile-time instrumentation if
the dependencies' sources should be instrumented:
```python theme={null}
# Are this rule's sources or any of the sources for its direct dependencies
# in deps instrumented?
if ctx.coverage_instrumented() or any([ctx.coverage_instrumented(dep) for dep in ctx.attr.deps]):
# Do something to turn on coverage for this compile action
```
Rules also should provide information about which attributes are relevant for
coverage with the `InstrumentedFilesInfo` provider, constructed using
[`coverage_common.instrumented_files_info`](/rules/lib/toplevel/coverage_common#instrumented_files_info).
The `dependency_attributes` parameter of `instrumented_files_info` should list
all runtime dependency attributes, including code dependencies like `deps` and
data dependencies like `data`. The `source_attributes` parameter should list the
rule's source files attributes if coverage instrumentation might be added:
```python theme={null}
def _example_library_impl(ctx):
...
return [
...
coverage_common.instrumented_files_info(
ctx,
dependency_attributes = ["deps", "data"],
# Omitted if coverage is not supported for this rule:
source_attributes = ["srcs", "hdrs"],
)
...
]
```
If `InstrumentedFilesInfo` is not returned, a default one is created with each
non-tool [dependency attribute](#dependency_attributes) that doesn't set
[`cfg`](#configuration) to `"exec"` in the attribute schema. in
`dependency_attributes`. (This isn't ideal behavior, since it puts attributes
like `srcs` in `dependency_attributes` instead of `source_attributes`, but it
avoids the need for explicit coverage configuration for all rules in the
dependency chain.)
#### Test rules
Test rules require additional setup to generate coverage reports. The rule
itself has to add the following implicit attributes:
```python theme={null}
my_test = rule(
...,
attrs = {
...,
# Implicit dependencies used by Bazel to generate coverage reports.
"_lcov_merger": attr.label(
default = configuration_field(fragment = "coverage", name = "output_generator"),
executable = True,
cfg = config.exec(exec_group = "test"),
),
"_collect_cc_coverage": attr.label(
default = "@bazel_tools//tools/test:collect_cc_coverage",
executable = True,
cfg = config.exec(exec_group = "test"),
)
},
test = True,
)
```
By using `configuration_field`, the dependency on the Java LCOV merger tool can
be avoided as long as coverage is not requested.
When the test is run, it should emit coverage information in the form of one or
more [LCOV files](https://manpages.debian.org/unstable/lcov/geninfo.1.en.html#TRACEFILE_FORMAT)
with unique names into the directory specified by the `COVERAGE_DIR` environment
variable. Bazel will then merge these files into a single LCOV file using the
`_lcov_merger` tool. If present, it will also collect C/C++ coverage using the
`_collect_cc_coverage` tool.
### Baseline coverage
Since coverage is only collected for code that ends up in the dependency tree of
a test, coverage reports can be misleading as they don't necessarily cover all
the code matched by the `--instrumentation_filter` flag.
For this reason, Bazel allows rules to specify baseline coverage files using the
`baseline_coverage_files` attribute of `ctx.instrumented_files_info`). These
files must be generated in LCOV format by a user-defined action and are supposed
to list all lines, branches, functions and/or blocks in the target's source
files (according to the `sources_attributes` and `extensions` parameters). For
source files in targets that are instrumented for coverage, Bazel merges their
baseline coverage into the combined coverage report generated with
`--combined_report` and thus ensures that untested files still show up as
uncovered.
If a rule doesn't provide any baseline coverage files, Bazel generates synthetic
coverage information that only mentions the source file paths, but doesn't
contain any information about their contents.
### Validation Actions
Sometimes you need to validate something about the build, and the
information required to do that validation is available only in artifacts
(source files or generated files). Because this information is in artifacts,
rules can't do this validation at analysis time because rules can't read
files. Instead, actions must do this validation at execution time. When
validation fails, the action will fail, and hence so will the build.
Examples of validations that might be run are static analysis, linting,
dependency and consistency checks, and style checks.
Validation actions can also help to improve build performance by moving parts
of actions that are not required for building artifacts into separate actions.
For example, if a single action that does compilation and linting can be
separated into a compilation action and a linting action, then the linting
action can be run as a validation action and run in parallel with other actions.
These "validation actions" often don't produce anything that is used elsewhere
in the build, since they only need to assert things about their inputs. This
presents a problem though: If a validation action doesn't produce anything that
is used elsewhere in the build, how does a rule get the action to run?
Historically, the approach was to have the validation action output an empty
file, and artificially add that output to the inputs of some other important
action in the build:
This works, because Bazel will always run the validation action when the compile
action is run, but this has significant drawbacks:
1. The validation action is in the critical path of the build. Because Bazel
thinks the empty output is required to run the compile action, it will run the
validation action first, even though the compile action will ignore the input.
This reduces parallelism and slows down builds.
2. If other actions in the build might run instead of the
compile action, then the empty outputs of validation actions need to be added to
those actions as well (`java_library`'s source jar output, for example). This is
also a problem if new actions that might run instead of the compile action are
added later, and the empty validation output is accidentally left off.
The solution to these problems is to use the Validations Output Group.
#### Validations Output Group
The Validations Output Group is an output group designed to hold the otherwise
unused outputs of validation actions, so that they don't need to be artificially
added to the inputs of other actions.
This group is special in that its outputs are always requested, regardless of
the value of the `--output_groups` flag, and regardless of how the target is
depended upon (for example, on the command line, as a dependency, or through
implicit outputs of the target). Note that normal caching and incrementality
still apply: if the inputs to the validation action have not changed and the
validation action previously succeeded, then the validation action won't be
run.
Using this output group still requires that validation actions output some file,
even an empty one. This might require wrapping some tools that normally don't
create outputs so that a file is created.
A target's validation actions are not run in three cases:
* When the target is depended upon as a tool
* When the target is depended upon as an implicit dependency (for example, an
attribute that starts with "\_")
* When the target is built in the exec configuration.
It is assumed that these targets have their own
separate builds and tests that would uncover any validation failures.
#### Using the Validations Output Group
The Validations Output Group is named `_validation` and is used like any other
output group:
```python theme={null}
def _rule_with_validation_impl(ctx):
ctx.actions.write(ctx.outputs.main, "main output\n")
ctx.actions.write(ctx.outputs.implicit, "implicit output\n")
validation_output = ctx.actions.declare_file(ctx.attr.name + ".validation")
ctx.actions.run(
outputs = [validation_output],
executable = ctx.executable._validation_tool,
arguments = [validation_output.path],
)
return [
DefaultInfo(files = depset([ctx.outputs.main])),
OutputGroupInfo(_validation = depset([validation_output])),
]
rule_with_validation = rule(
implementation = _rule_with_validation_impl,
outputs = {
"main": "%{name}.main",
"implicit": "%{name}.implicit",
},
attrs = {
"_validation_tool": attr.label(
default = Label("//validation_actions:validation_tool"),
executable = True,
cfg = "exec"
),
}
)
```
Notice that the validation output file is not added to the `DefaultInfo` or the
inputs to any other action. The validation action for a target of this rule kind
will still run if the target is depended upon by label, or any of the target's
implicit outputs are directly or indirectly depended upon.
It is usually important that the outputs of validation actions only go into the
validation output group, and are not added to the inputs of other actions, as
this could defeat parallelism gains. Note however that Bazel doesn't
have any special checking to enforce this. Therefore, you should test
that validation action outputs are not added to the inputs of any actions in the
tests for Starlark rules. For example:
```python theme={null}
load("@bazel_skylib//lib:unittest.bzl", "analysistest")
def _validation_outputs_test_impl(ctx):
env = analysistest.begin(ctx)
actions = analysistest.target_actions(env)
target = analysistest.target_under_test(env)
validation_outputs = target.output_groups._validation.to_list()
for action in actions:
for validation_output in validation_outputs:
if validation_output in action.inputs.to_list():
analysistest.fail(env,
"%s is a validation action output, but is an input to action %s" % (
validation_output, action))
return analysistest.end(env)
validation_outputs_test = analysistest.make(_validation_outputs_test_impl)
```
#### Validation Actions Flag
Running validation actions is controlled by the `--run_validations` command line
flag, which defaults to true.
## Deprecated features
### Deprecated predeclared outputs
There are two **deprecated** ways of using predeclared outputs:
* The [`outputs`](/rules/lib/globals/bzl#rule.outputs) parameter of `rule` specifies
a mapping between output attribute names and string templates for generating
predeclared output labels. Prefer using non-predeclared outputs and
explicitly adding outputs to `DefaultInfo.files`. Use the rule target's
label as input for rules which consume the output instead of a predeclared
output's label.
* For [executable rules](#executable-rules), `ctx.outputs.executable` refers
to a predeclared executable output with the same name as the rule target.
Prefer declaring the output explicitly, for example with
`ctx.actions.declare_file(ctx.label.name)`, and ensure that the command that
generates the executable sets its permissions to allow execution. Explicitly
pass the executable output to the `executable` parameter of `DefaultInfo`.
### Runfiles features to avoid
[`ctx.runfiles`](/rules/lib/builtins/ctx#runfiles) and the [`runfiles`](/rules/lib/builtins/runfiles)
type have a complex set of features, many of which are kept for legacy reasons.
The following recommendations help reduce complexity:
* **Avoid** use of the `collect_data` and `collect_default` modes of
[`ctx.runfiles`](/rules/lib/builtins/ctx#runfiles). These modes implicitly collect
runfiles across certain hardcoded dependency edges in confusing ways.
Instead, add files using the `files` or `transitive_files` parameters of
`ctx.runfiles`, or by merging in runfiles from dependencies with
`runfiles = runfiles.merge(dep[DefaultInfo].default_runfiles)`.
* **Avoid** use of the `data_runfiles` and `default_runfiles` of the
`DefaultInfo` constructor. Specify `DefaultInfo(runfiles = ...)` instead.
The distinction between "default" and "data" runfiles is maintained for
legacy reasons. For example, some rules put their default outputs in
`data_runfiles`, but not `default_runfiles`. Instead of using
`data_runfiles`, rules should *both* include default outputs and merge in
`default_runfiles` from attributes which provide runfiles (often
[`data`](/reference/be/common-definitions#common-attributes.data)).
* When retrieving `runfiles` from `DefaultInfo` (generally only for merging
runfiles between the current rule and its dependencies), use
`DefaultInfo.default_runfiles`, **not** `DefaultInfo.data_runfiles`.
### Migrating from legacy providers
Historically, Bazel providers were simple fields on the `Target` object. They
were accessed using the dot operator, and they were created by putting the field
in a [`struct`](/rules/lib/builtins/struct) returned by the rule's
implementation function instead of a list of provider objects:
```python theme={null}
return struct(example_info = struct(headers = depset(...)))
```
Such providers can be retrieved from the corresponding field of the `Target` object:
```python theme={null}
transitive_headers = [hdr.example_info.headers for hdr in ctx.attr.hdrs]
```
*This style is deprecated and should not be used in new code;* see following for
information that may help you migrate. The new provider mechanism avoids name
clashes. It also supports data hiding, by requiring any code accessing a
provider instance to retrieve it using the provider symbol.
For the moment, legacy providers are still supported. A rule can return both
legacy and modern providers as follows:
```python theme={null}
def _old_rule_impl(ctx):
...
legacy_data = struct(x = "foo", ...)
modern_data = MyInfo(y = "bar", ...)
# When any legacy providers are returned, the top-level returned value is a
# struct.
return struct(
# One key = value entry for each legacy provider.
legacy_info = legacy_data,
...
# Additional modern providers:
providers = [modern_data, ...])
```
If `dep` is the resulting `Target` object for an instance of this rule, the
providers and their contents can be retrieved as `dep.legacy_info.x` and
`dep[MyInfo].y`.
In addition to `providers`, the returned struct can also take several other
fields that have special meaning (and thus don't create a corresponding legacy
provider):
* The fields `files`, `runfiles`, `data_runfiles`, `default_runfiles`, and
`executable` correspond to the same-named fields of
[`DefaultInfo`](/rules/lib/providers/DefaultInfo). It is not allowed to specify any of
these fields while also returning a `DefaultInfo` provider.
* The field `output_groups` takes a struct value and corresponds to an
[`OutputGroupInfo`](/rules/lib/providers/OutputGroupInfo).
In [`provides`](/rules/lib/globals/bzl#rule.provides) declarations of rules, and in
[`providers`](/rules/lib/toplevel/attr#label_list.providers) declarations of dependency
attributes, legacy providers are passed in as strings and modern providers are
passed in by their `Info` symbol. Be sure to change from strings to symbols
when migrating. For complex or large rule sets where it is difficult to update
all rules atomically, you may have an easier time if you follow this sequence of
steps:
1. Modify the rules that produce the legacy provider to produce both the legacy
and modern providers, using the preceding syntax. For rules that declare they
return the legacy provider, update that declaration to include both the
legacy and modern providers.
2. Modify the rules that consume the legacy provider to instead consume the
modern provider. If any attribute declarations require the legacy provider,
also update them to instead require the modern provider. Optionally, you can
interleave this work with step 1 by having consumers accept or require either
provider: Test for the presence of the legacy provider using
`hasattr(target, 'foo')`, or the new provider using `FooInfo in target`.
3. Fully remove the legacy provider from all rules.
# Toolchains
Source: https://bazel.build/extending/toolchains
This page describes the toolchain framework, which is a way for rule authors to
decouple their rule logic from platform-based selection of tools. It is
recommended to read the [rules](/extending/rules) and [platforms](/extending/platforms)
pages before continuing. This page covers why toolchains are needed, how to
define and use them, and how Bazel selects an appropriate toolchain based on
platform constraints.
## Motivation
Let's first look at the problem toolchains are designed to solve. Suppose you
are writing rules to support the "bar" programming language. Your `bar_binary`
rule would compile `*.bar` files using the `barc` compiler, a tool that itself
is built as another target in your workspace. Since users who write `bar_binary`
targets shouldn't have to specify a dependency on the compiler, you make it an
implicit dependency by adding it to the rule definition as a private attribute.
```python theme={null}
bar_binary = rule(
implementation = _bar_binary_impl,
attrs = {
"srcs": attr.label_list(allow_files = True),
...
"_compiler": attr.label(
default = "//bar_tools:barc_linux", # the compiler running on linux
providers = [BarcInfo],
),
},
)
```
`//bar_tools:barc_linux` is now a dependency of every `bar_binary` target, so
it'll be built before any `bar_binary` target. It can be accessed by the rule's
implementation function just like any other attribute:
```python theme={null}
BarcInfo = provider(
doc = "Information about how to invoke the barc compiler.",
# In the real world, compiler_path and system_lib might hold File objects,
# but for simplicity they are strings for this example. arch_flags is a list
# of strings.
fields = ["compiler_path", "system_lib", "arch_flags"],
)
def _bar_binary_impl(ctx):
...
info = ctx.attr._compiler[BarcInfo]
command = "%s -l %s %s" % (
info.compiler_path,
info.system_lib,
" ".join(info.arch_flags),
)
...
```
The issue here is that the compiler's label is hardcoded into `bar_binary`, yet
different targets may need different compilers depending on what platform they
are being built for and what platform they are being built on -- called the
*target platform* and *execution platform*, respectively. Furthermore, the rule
author does not necessarily even know all the available tools and platforms, so
it is not feasible to hardcode them in the rule's definition.
A less-than-ideal solution would be to shift the burden onto users, by making
the `_compiler` attribute non-private. Then individual targets could be
hardcoded to build for one platform or another.
```python theme={null}
bar_binary(
name = "myprog_on_linux",
srcs = ["mysrc.bar"],
compiler = "//bar_tools:barc_linux",
)
bar_binary(
name = "myprog_on_windows",
srcs = ["mysrc.bar"],
compiler = "//bar_tools:barc_windows",
)
```
You can improve on this solution by using `select` to choose the `compiler`
[based on the platform](/docs/configurable-attributes):
```python theme={null}
config_setting(
name = "on_linux",
constraint_values = [
"@platforms//os:linux",
],
)
config_setting(
name = "on_windows",
constraint_values = [
"@platforms//os:windows",
],
)
bar_binary(
name = "myprog",
srcs = ["mysrc.bar"],
compiler = select({
":on_linux": "//bar_tools:barc_linux",
":on_windows": "//bar_tools:barc_windows",
}),
)
```
But this is tedious and a bit much to ask of every single `bar_binary` user.
If this style is not used consistently throughout the workspace, it leads to
builds that work fine on a single platform but fail when extended to
multi-platform scenarios. It also does not address the problem of adding support
for new platforms and compilers without modifying existing rules or targets.
The toolchain framework solves this problem by adding an extra level of
indirection. Essentially, you declare that your rule has an abstract dependency
on *some* member of a family of targets (a toolchain type), and Bazel
automatically resolves this to a particular target (a toolchain) based on the
applicable platform constraints. Neither the rule author nor the target author
need know the complete set of available platforms and toolchains.
## Writing rules that use toolchains
Under the toolchain framework, instead of having rules depend directly on tools,
they instead depend on *toolchain types*. A toolchain type is a simple target
that represents a class of tools that serve the same role for different
platforms. For instance, you can declare a type that represents the bar
compiler:
```python theme={null}
# By convention, toolchain_type targets are named "toolchain_type" and
# distinguished by their package path. So the full path for this would be
# //bar_tools:toolchain_type.
toolchain_type(name = "toolchain_type")
```
The rule definition in the previous section is modified so that instead of
taking in the compiler as an attribute, it declares that it consumes a
`//bar_tools:toolchain_type` toolchain.
```python theme={null}
bar_binary = rule(
implementation = _bar_binary_impl,
attrs = {
"srcs": attr.label_list(allow_files = True),
...
# No `_compiler` attribute anymore.
},
toolchains = ["//bar_tools:toolchain_type"],
)
```
The implementation function now accesses this dependency under `ctx.toolchains`
instead of `ctx.attr`, using the toolchain type as the key.
```python theme={null}
def _bar_binary_impl(ctx):
...
info = ctx.toolchains["//bar_tools:toolchain_type"].barcinfo
# The rest is unchanged.
command = "%s -l %s %s" % (
info.compiler_path,
info.system_lib,
" ".join(info.arch_flags),
)
...
```
`ctx.toolchains["//bar_tools:toolchain_type"]` returns the
[`ToolchainInfo` provider](/rules/lib/toplevel/platform_common#ToolchainInfo)
of whatever target Bazel resolved the toolchain dependency to. The fields of the
`ToolchainInfo` object are set by the underlying tool's rule; in the next
section, this rule is defined such that there is a `barcinfo` field that wraps
a `BarcInfo` object.
Bazel's procedure for resolving toolchains to targets is described
[below](#toolchain-resolution). Only the resolved toolchain target is actually
made a dependency of the `bar_binary` target, not the whole space of candidate
toolchains.
### Mandatory and Optional Toolchains
By default, when a rule expresses a toolchain type dependency using a bare label
(as shown above), the toolchain type is considered to be **mandatory**. If Bazel
is unable to find a matching toolchain (see
[Toolchain resolution](#toolchain-resolution) below) for a mandatory toolchain
type, this is an error and analysis halts.
It is possible instead to declare an **optional** toolchain type dependency, as
follows:
```python theme={null}
bar_binary = rule(
...
toolchains = [
config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = False),
],
)
```
When an optional toolchain type cannot be resolved, analysis continues, and the
result of `ctx.toolchains["//bar_tools:toolchain_type"]` is `None`.
The [`config_common.toolchain_type`](/rules/lib/toplevel/config_common#toolchain_type)
function defaults to mandatory.
The following forms can be used:
* Mandatory toolchain types:
* `toolchains = ["//bar_tools:toolchain_type"]`
* `toolchains = [config_common.toolchain_type("//bar_tools:toolchain_type")]`
* `toolchains = [config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = True)]`
* Optional toolchain types:
* `toolchains = [config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = False)]`
```python theme={null}
bar_binary = rule(
...
toolchains = [
"//foo_tools:toolchain_type",
config_common.toolchain_type("//bar_tools:toolchain_type", mandatory = False),
],
)
```
You can mix and match forms in the same rule, also. However, if the same
toolchain type is listed multiple times, it will take the most strict version,
where mandatory is more strict than optional.
### Writing aspects that use toolchains
Aspects have access to the same toolchain API as rules: you can define required
toolchain types, access toolchains via the context, and use them to generate new
actions using the toolchain.
```py theme={null}
bar_aspect = aspect(
implementation = _bar_aspect_impl,
attrs = {},
toolchains = ['//bar_tools:toolchain_type'],
)
def _bar_aspect_impl(target, ctx):
toolchain = ctx.toolchains['//bar_tools:toolchain_type']
# Use the toolchain provider like in a rule.
return []
```
## Defining toolchains
To define some toolchains for a given toolchain type, you need three things:
1. A language-specific rule representing the kind of tool or tool suite. By
convention this rule's name is suffixed with "\_toolchain".
1. **Note:** The `\_toolchain` rule cannot create any build actions.
Rather, it collects artifacts from other rules and forwards them to the
rule that uses the toolchain. That rule is responsible for creating all
build actions.
2. Several targets of this rule type, representing versions of the tool or tool
suite for different platforms.
3. For each such target, an associated target of the generic
[`toolchain`](/reference/be/platforms-and-toolchains#toolchain)
rule, to provide metadata used by the toolchain framework. This `toolchain`
target also refers to the `toolchain_type` associated with this toolchain.
This means that a given `_toolchain` rule could be associated with any
`toolchain_type`, and that only in a `toolchain` instance that uses
this `_toolchain` rule that the rule is associated with a `toolchain_type`.
For our running example, here's a definition for a `bar_toolchain` rule. Our
example has only a compiler, but other tools such as a linker could also be
grouped underneath it.
```python theme={null}
def _bar_toolchain_impl(ctx):
toolchain_info = platform_common.ToolchainInfo(
barcinfo = BarcInfo(
compiler_path = ctx.attr.compiler_path,
system_lib = ctx.attr.system_lib,
arch_flags = ctx.attr.arch_flags,
),
)
return [toolchain_info]
bar_toolchain = rule(
implementation = _bar_toolchain_impl,
attrs = {
"compiler_path": attr.string(),
"system_lib": attr.string(),
"arch_flags": attr.string_list(),
},
)
```
The rule must return a `ToolchainInfo` provider, which becomes the object that
the consuming rule retrieves using `ctx.toolchains` and the label of the
toolchain type. `ToolchainInfo`, like `struct`, can hold arbitrary field-value
pairs. The specification of exactly what fields are added to the `ToolchainInfo`
should be clearly documented at the toolchain type. In this example, the values
return wrapped in a `BarcInfo` object to reuse the schema defined above; this
style may be useful for validation and code reuse.
Now you can define targets for specific `barc` compilers.
```python theme={null}
bar_toolchain(
name = "barc_linux",
arch_flags = [
"--arch=Linux",
"--debug_everything",
],
compiler_path = "/path/to/barc/on/linux",
system_lib = "/usr/lib/libbarc.so",
)
bar_toolchain(
name = "barc_windows",
arch_flags = [
"--arch=Windows",
# Different flags, no debug support on windows.
],
compiler_path = "C:\\path\\on\\windows\\barc.exe",
system_lib = "C:\\path\\on\\windows\\barclib.dll",
)
```
Finally, you create `toolchain` definitions for the two `bar_toolchain` targets.
These definitions link the language-specific targets to the toolchain type and
provide the constraint information that tells Bazel when the toolchain is
appropriate for a given platform.
```python theme={null}
toolchain(
name = "barc_linux_toolchain",
exec_compatible_with = [
"@platforms//os:linux",
"@platforms//cpu:x86_64",
],
target_compatible_with = [
"@platforms//os:linux",
"@platforms//cpu:x86_64",
],
toolchain = ":barc_linux",
toolchain_type = ":toolchain_type",
)
toolchain(
name = "barc_windows_toolchain",
exec_compatible_with = [
"@platforms//os:windows",
"@platforms//cpu:x86_64",
],
target_compatible_with = [
"@platforms//os:windows",
"@platforms//cpu:x86_64",
],
toolchain = ":barc_windows",
toolchain_type = ":toolchain_type",
)
```
The use of relative path syntax above suggests these definitions are all in the
same package, but there's no reason the toolchain type, language-specific
toolchain targets, and `toolchain` definition targets can't all be in separate
packages.
See the [`go_toolchain`](https://github.com/bazelbuild/rules_go/blob/master/go/private/go_toolchain.bzl)
for a real-world example.
### Toolchains and configurations
An important question for rule authors is, when a `bar_toolchain` target is
analyzed, what [configuration](/reference/glossary#configuration) does it see, and what transitions
should be used for dependencies? The example above uses string attributes, but
what would happen for a more complicated toolchain that depends on other targets
in the Bazel repository?
Let's see a more complex version of `bar_toolchain`:
```python theme={null}
def _bar_toolchain_impl(ctx):
# The implementation is mostly the same as above, so skipping.
pass
bar_toolchain = rule(
implementation = _bar_toolchain_impl,
attrs = {
"compiler": attr.label(
executable = True,
mandatory = True,
cfg = "exec",
),
"system_lib": attr.label(
mandatory = True,
cfg = "target",
),
"arch_flags": attr.string_list(),
},
)
```
The use of [`attr.label`](/rules/lib/toplevel/attr#label) is the same as for a standard rule,
but the meaning of the `cfg` parameter is slightly different.
When a target (the "parent") depends on a toolchain via toolchain resolution,
Bazel applies a special configuration transition called the "toolchain transition".
In this transition Bazel keeps the overall configuration identical, but forces
the toolchain to use the same execution platform as the parent. Without this,
toolchain resolution could pick a different execution platform for the
toolchain, and the tools it provides might not be runnable for the parent's
actions.
This alignment of execution platforms guarantees that any dependencies of the
toolchain declared with `cfg = "exec"` are built so they can run where the
parent's actions run.
Dependencies declared with `cfg = "target"` (or which omit `cfg`, since
"target" is the default) are built for the parent's target platform. This lets
the toolchain contribute both runtime libraries and build-time tools.
In practice:
* `cfg = "exec"`: build artifacts intended to run during the build (e.g.
the `compiler` tool) and therefore for the execution platform.
* `cfg = "target"`: build artifacts intended to be linked into or shipped with
the final output (e.g. the `system_lib`) and therefore for the target
platform.
The system libraries must be built for the same target platform as the final
artifact, while the compiler must be runnable on the execution platform.
### Selecting `exec` dependencies
For toolchain config rules, adding a `select()` to an attribute with `cfg = "exec"`
does **not** make the `select()` use the exec configuration.
It will still be resolved under the **target** configuration.
Assuming the target platform is not matching any of these constraints, the select for the compiler
will fail to analyze.
```python theme={null}
bar_toolchain(
name = "barc_omni",
compiler = select({
"@platforms//os:linux": Label(":linux_compiler"),
"@platforms//os:windows": Label(":windows_compiler"),
"//some/exec:platform": Label(":special_compiler"),
},
no_match_error = "No compiler for this execution platform",
}),
# <...>
)
```
A known workaround for this is to defer the evaluation behind another target,
e.g. [`alias()`](/reference/be/general#alias).
This analyzes the `select` inside the alias under the exec configuration.
```python theme={null}
alias(
name = "host_specific_compiler",
actual = select({
"@platforms//os:linux": Label(":linux_compiler"),
"@platforms//os:windows": Label(":windows_compiler"),
"//some/exec:platform": Label(":special_compiler"),
},
no_match_error = "No compiler for this execution platform",
),
)
bar_toolchain(
name = "barc_omni",
compiler = ":host_specific_compiler",
# <...>
)
```
## Registering and building with toolchains
At this point all the building blocks are assembled, and you just need to make
the toolchains available to Bazel's resolution procedure. This is done by
registering the toolchain, either in a `MODULE.bazel` file using
`register_toolchains()`, or by passing the toolchains' labels on the command
line using the `--extra_toolchains` flag.
```python theme={null}
register_toolchains(
"//bar_tools:barc_linux_toolchain",
"//bar_tools:barc_windows_toolchain",
# Target patterns are also permitted, so you could have also written:
# "//bar_tools:all",
# or even
# "//bar_tools/...",
)
```
When using target patterns to register toolchains, the order in which the
individual toolchains are registered is determined by the following rules:
* The toolchains defined in a subpackage of a package are registered before the
toolchains defined in the package itself.
* Within a package, toolchains are registered in the lexicographical order of
their names.
Now when you build a target that depends on a toolchain type, an appropriate
toolchain will be selected based on the target and execution platforms.
```python theme={null}
# my_pkg/BUILD
platform(
name = "my_target_platform",
constraint_values = [
"@platforms//os:linux",
],
)
bar_binary(
name = "my_bar_binary",
...
)
```
```sh theme={null}
bazel build //my_pkg:my_bar_binary --platforms=//my_pkg:my_target_platform
```
Bazel will see that `//my_pkg:my_bar_binary` is being built with a platform that
has `@platforms//os:linux` and therefore resolve the
`//bar_tools:toolchain_type` reference to `//bar_tools:barc_linux_toolchain`.
This will end up building `//bar_tools:barc_linux` but not
`//bar_tools:barc_windows`.
## Toolchain resolution
Note: [Some Bazel rules](/concepts/platforms#status) do not yet support
toolchain resolution.
For each target that uses toolchains, Bazel's toolchain resolution procedure
determines the target's concrete toolchain dependencies. The procedure takes as
input a set of required toolchain types, the target platform, the list of
available execution platforms, and the list of available toolchains. Its outputs
are a selected toolchain for each toolchain type as well as a selected execution
platform for the current target.
The available execution platforms and toolchains are gathered from the
external dependency graph via
[`register_execution_platforms`](/rules/lib/globals/module#register_execution_platforms)
and
[`register_toolchains`](/rules/lib/globals/module#register_toolchains) calls in
`MODULE.bazel` files.
Additional execution platforms and toolchains may also be specified on the
command line via
[`--extra_execution_platforms`](/reference/command-line-reference#flag--extra_execution_platforms)
and
[`--extra_toolchains`](/reference/command-line-reference#flag--extra_toolchains).
The host platform is automatically included as an available execution platform.
Available platforms and toolchains are tracked as ordered lists for determinism,
with preference given to earlier items in the list.
The set of available toolchains, in priority order, is created from
`--extra_toolchains` and `register_toolchains`:
1. Toolchains registered using `--extra_toolchains` are added first. (Within
these, the **last** toolchain has highest priority.)
2. Toolchains registered using `register_toolchains` in the transitive external
dependency graph, in the following order: (Within these, the **first**
mentioned toolchain has highest priority.)
3. Toolchains registered by the root module (as in, the `MODULE.bazel` at the
workspace root);
4. Toolchains registered in the user's `WORKSPACE` file, including in any
macros invoked from there;
5. Toolchains registered by non-root modules (as in, dependencies specified by
the root module, and their dependencies, and so forth);
6. Toolchains registered in the "WORKSPACE suffix"; this is only used by
certain native rules bundled with the Bazel installation.
**NOTE:** [Pseudo-targets like `:all`, `:*`, and `/...`](/run/build#specifying-build-targets) are ordered by Bazel's package
loading mechanism, which uses a lexicographic ordering.
The resolution steps are as follows.
1. A `target_compatible_with` or `exec_compatible_with` clause *matches* a
platform if, for each `constraint_value` in its list, the platform also has
that `constraint_value` (either explicitly or as a default).
If the platform has `constraint_value`s from `constraint_setting`s not
referenced by the clause, these do not affect matching.
2. If the target being built specifies the
[`exec_compatible_with` attribute](/reference/be/common-definitions#common.exec_compatible_with)
(or its rule definition specifies the
[`exec_compatible_with` argument](/rules/lib/globals/bzl#rule.exec_compatible_with)),
the list of available execution platforms is filtered to remove
any that do not match the execution constraints.
3. The list of available toolchains is filtered to remove any toolchains
specifying `target_settings` that don't match the current configuration.
4. For each available execution platform, you associate each toolchain type with
the first available toolchain, if any, that is compatible with this execution
platform and the target platform.
5. Any execution platform that failed to find a compatible mandatory toolchain
for one of its toolchain types is ruled out. Of the remaining platforms, the
first one becomes the current target's execution platform, and its associated
toolchains (if any) become dependencies of the target.
The chosen execution platform is used to run all actions that the target
generates.
In cases where the same target can be built in multiple configurations (such as
for different CPUs) within the same build, the resolution procedure is applied
independently to each version of the target.
If the rule uses [execution groups](/extending/exec-groups), each execution
group performs toolchain resolution separately, and each has its own execution
platform and toolchains.
**TIP:** For a toolchain to match a platform, the platform must define *all* of
the toolchain's constraints. But the reverse isn't true: the platform may define
additional constraints not specified by the toolchain. This lets developers
define arbitrarily precise platforms that don't lose toolchain compatibility
because of unrelated hardware variants.
## Debugging toolchains
If you are adding toolchain support to an existing rule, use the
`--toolchain_resolution_debug=regex` flag. During toolchain resolution, the flag
provides verbose output for toolchain types or target names that match the regex variable. You
can use `.*` to output all information. Bazel will output names of toolchains it
checks and skips during the resolution process.
For example, to debug toolchain selection for all actions created directly by
`//my:target`:
```sh theme={null}
$ bazel build //my:all --toolchain_resolution_debug=//my:target
```
To debug toolchain selection for all actions over all build targets:
```sh theme={null}
$ bazel build //my:all --toolchain_resolution_debug=.*
```
If you'd like to see which [`cquery`](/query/cquery) dependencies are from toolchain
resolution, use `cquery`'s [`--transitions`](/query/cquery#transitions) flag:
```
# Find all direct dependencies of //cc:my_cc_lib. This includes explicitly
# declared dependencies, implicit dependencies, and toolchain dependencies.
$ bazel cquery 'deps(//cc:my_cc_lib, 1)'
//cc:my_cc_lib (96d6638)
@bazel_tools//tools/cpp:toolchain (96d6638)
@bazel_tools//tools/def_parser:def_parser (HOST)
//cc:my_cc_dep (96d6638)
@local_config_platform//:host (96d6638)
@bazel_tools//tools/cpp:toolchain_type (96d6638)
//:default_host_platform (96d6638)
@local_config_cc//:cc-compiler-k8 (HOST)
//cc:my_cc_lib.cc (null)
@bazel_tools//tools/cpp:grep-includes (HOST)
# Which of these are from toolchain resolution?
$ bazel cquery 'deps(//cc:my_cc_lib, 1)' --transitions=lite | grep "toolchain dependency"
[toolchain dependency]#@local_config_cc//:cc-compiler-k8#HostTransition -> b6df211
```
# Action Graph Query (aquery)
Source: https://bazel.build/query/aquery
The `aquery` command allows you to query for actions in your build graph.
It operates on the post-analysis Configured Target Graph and exposes
information about **Actions, Artifacts and their relationships.**
`aquery` is useful when you are interested in the properties of the Actions/Artifacts
generated from the Configured Target Graph. For example, the actual commands run
and their inputs/outputs/mnemonics.
The tool accepts several command-line [options](#command-options).
Notably, the aquery command runs on top of a regular Bazel build and inherits
the set of options available during a build.
It supports the same set of functions that is also available to traditional
`query` but `siblings`, `buildfiles` and
`tests`.
An example `aquery` output (without specific details):
```
$ bazel aquery 'deps(//some:label)'
action 'Writing file some_file_name'
Mnemonic: ...
Target: ...
Configuration: ...
ActionKey: ...
Inputs: [...]
Outputs: [...]
```
## Basic syntax
A simple example of the syntax for `aquery` is as follows:
`bazel aquery "aquery_function(function(//target))"`
The query expression (in quotes) consists of the following:
* `aquery_function(...)`: functions specific to `aquery`.
More details [below](#using-aquery-functions).
* `function(...)`: the standard [functions](/query/language#functions)
as traditional `query`.
* `//target` is the label to the interested target.
```
# aquery examples:
# Get the action graph generated while building //src/target_a
$ bazel aquery '//src/target_a'
# Get the action graph generated while building all dependencies of //src/target_a
$ bazel aquery 'deps(//src/target_a)'
# Get the action graph generated while building all dependencies of //src/target_a
# whose inputs filenames match the regex ".*cpp".
$ bazel aquery 'inputs(".*cpp", deps(//src/target_a))'
```
## Using aquery functions
There are three `aquery` functions:
* `inputs`: filter actions by inputs.
* `outputs`: filter actions by outputs
* `mnemonic`: filter actions by mnemonic
`expr ::= inputs(word, expr)`
The `inputs` operator returns the actions generated from building `expr`,
whose input filenames match the regex provided by `word`.
`$ bazel aquery 'inputs(".*cpp", deps(//src/target_a))'`
`outputs` and `mnemonic` functions share a similar syntax.
You can also combine functions to achieve the AND operation. For example:
```
$ bazel aquery 'mnemonic("Cpp.*", (inputs(".*cpp", inputs("foo.*", //src/target_a))))'
```
The above command would find all actions involved in building `//src/target_a`,
whose mnemonics match `"Cpp.*"` and inputs match the patterns
`".*cpp"` and `"foo.*"`.
Important: aquery functions can't be nested inside non-aquery functions.
Conceptually, this makes sense since the output of aquery functions is Actions,
not Configured Targets.
An example of the syntax error produced:
```
$ bazel aquery 'deps(inputs(".*cpp", //src/target_a))'
ERROR: aquery filter functions (inputs, outputs, mnemonic) produce actions,
and therefore can't be the input of other function types: deps
deps(inputs(".*cpp", //src/target_a))
```
## Options
### Build options
`aquery` runs on top of a regular Bazel build and thus inherits the set of
[options](/reference/command-line-reference#build-options)
available during a build.
### Aquery options
#### `--output=(text|summary|commands|proto|jsonproto|textproto), default=text`
The default output format (`text`) is human-readable,
use `proto`, `textproto`, or `jsonproto` for machine-readable format.
The proto message is `analysis.ActionGraphContainer`.
The `commands` output format prints a list of build commands with
one command per line.
In general, do not depend on the order of output. For more information,
see the [core query ordering contract](/query/language#graph-order).
#### `--include_commandline, default=true`
Includes the content of the action command lines in the output (potentially large).
#### `--include_artifacts, default=true`
Includes names of the action inputs and outputs in the output (potentially large).
#### `--include_aspects, default=true`
Whether to include Aspect-generated actions in the output.
#### `--include_param_files, default=false`
Include the content of the param files used in the command (potentially large).
Warning: Enabling this flag will automatically enable the `--include_commandline` flag.
#### `--include_file_write_contents, default=false`
Include file contents for the `actions.write()` action and the contents of the
manifest file for the `SourceSymlinkManifest` action The file contents is
returned in the `file_contents` field with `--output=`xxx`proto`.
With `--output=text`, the output has
```
FileWriteContents: []
```
line
#### `--skyframe_state, default=false`
Without performing extra analysis, dump the Action Graph from Skyframe.
Note: Specifying a target with `--skyframe_state` is currently not supported.
This flag is only available with `--output=proto` or `--output=textproto`.
## Other tools and features
### Querying against the state of Skyframe
[Skyframe](/reference/skyframe) is the evaluation and
incrementality model of Bazel. On each instance of Bazel server, Skyframe stores the dependency graph
constructed from the previous runs of the [Analysis phase](/run/build#analysis).
In some cases, it is useful to query the Action Graph on Skyframe.
An example use case would be:
1. Run `bazel build //target_a`
2. Run `bazel build //target_b`
3. File `foo.out` was generated.
*As a Bazel user, I want to determine if `foo.out` was generated from building
`//target_a` or `//target_b`*.
One could run `bazel aquery 'outputs("foo.out", //target_a)'` and
`bazel aquery 'outputs("foo.out", //target_b)'` to figure out the action responsible
for creating `foo.out`, and in turn the target. However, the number of different
targets previously built can be larger than 2, which makes running multiple `aquery`
commands a hassle.
As an alternative, the `--skyframe_state` flag can be used:
```
# List all actions on Skyframe's action graph
$ bazel aquery --output=proto --skyframe_state
# or
# List all actions on Skyframe's action graph, whose output matches "foo.out"
$ bazel aquery --output=proto --skyframe_state 'outputs("foo.out")'
```
With `--skyframe_state` mode, `aquery` takes the content of the Action Graph
that Skyframe keeps on the instance of Bazel, (optionally) performs filtering on it and
outputs the content, without re-running the analysis phase.
#### Special considerations
##### Output format
`--skyframe_state` is currently only available for `--output=proto`
and `--output=textproto`
##### Non-inclusion of target labels in the query expression
Currently, `--skyframe_state` queries the whole action graph that exists on Skyframe,
regardless of the targets. Having the target label specified in the query together with
`--skyframe_state` is considered a syntax error:
```
# WRONG: Target Included
$ bazel aquery --output=proto --skyframe_state **//target_a**
ERROR: Error while parsing '//target_a)': Specifying build target(s) [//target_a] with --skyframe_state is currently not supported.
# WRONG: Target Included
$ bazel aquery --output=proto --skyframe_state 'inputs(".*.java", **//target_a**)'
ERROR: Error while parsing '//target_a)': Specifying build target(s) [//target_a] with --skyframe_state is currently not supported.
# CORRECT: Without Target
$ bazel aquery --output=proto --skyframe_state
$ bazel aquery --output=proto --skyframe_state 'inputs(".*.java")'
```
### Comparing aquery outputs
You can compare the outputs of two different aquery invocations using the `aquery_differ` tool.
For instance: when you make some changes to your rule definition and want to verify that the
command lines being run did not change. `aquery_differ` is the tool for that.
The tool is available in the [bazelbuild/bazel](https://github.com/bazelbuild/bazel/tree/master/scripts/aquery_differ) repository.
To use it, clone the repository to your local machine. An example usage:
```
$ bazel run //scripts/aquery_differ -- \
--before=/path/to/before.proto \
--after=/path/to/after.proto \
--input_type=proto \
--attrs=cmdline \
--attrs=inputs
```
The above command returns the difference between the `before` and `after` aquery outputs:
which actions were present in one but not the other, which actions have different
command line/inputs in each aquery output, ...). The result of running the above command would be:
```
Aquery output 'after' change contains an action that generates the following outputs that aquery output 'before' change doesn't:
...
/list of output files/
...
[cmdline]
Difference in the action that generates the following output(s):
/path/to/abc.out
--- /path/to/before.proto
+++ /path/to/after.proto
@@ -1,3 +1,3 @@
...
/cmdline diff, in unified diff format/
...
```
#### Command options
`--before, --after`: The aquery output files to be compared
`--input_type=(proto|text_proto), default=proto`: the format of the input
files. Support is provided for `proto` and `textproto` aquery output.
`--attrs=(cmdline|inputs), default=cmdline`: the attributes of actions
to be compared.
### Aspect-on-aspect
It is possible for [Aspects](/extending/aspects)
to be applied on top of each other. The aquery output of the action generated by
these Aspects would then include the *Aspect path*, which is the sequence of
Aspects applied to the target which generated the action.
An example of Aspect-on-Aspect:
```
t0
^
| <- a1
t1
^
| <- a2
t2
```
Let ti be a target of rule ri, which applies an Aspect ai
to its dependencies.
Assume that a2 generates an action X when applied to target t0. The text output of
`bazel aquery --include_aspects 'deps(//t2)'` for action X would be:
```
action ...
Mnemonic: ...
Target: //my_pkg:t0
Configuration: ...
AspectDescriptors: [//my_pkg:rule.bzl%**a2**(foo=...)
-> //my_pkg:rule.bzl%**a1**(bar=...)]
...
```
This means that action `X` was generated by Aspect `a2` applied onto
`a1(t0)`, where `a1(t0)` is the result of Aspect `a1` applied
onto target `t0`.
Each `AspectDescriptor` has the following format:
```
AspectClass([param=value,...])
```
`AspectClass` could be the name of the Aspect class (for native Aspects) or
`bzl_file%aspect_name` (for Starlark Aspects). `AspectDescriptor` are
sorted in topological order of the
[dependency graph](/extending/aspects#aspect_basics).
### Linking with the JSON profile
While aquery provides information about the actions being run in a build (why they're being run,
their inputs/outputs), the [JSON profile](/rules/performance#performance-profiling)
tells us the timing and duration of their execution.
It is possible to combine these 2 sets of information via a common denominator: an action's primary output.
To include actions' outputs in the JSON profile, generate the profile with
`--experimental_include_primary_output --noslim_profile`.
Slim profiles are incompatible with the inclusion of primary outputs. An action's primary output
is included by default by aquery.
We don't currently provide a canonical tool to combine these 2 data sources, but you should be
able to build your own script with the above information.
## Known issues
### Handling shared actions
Sometimes actions are
[shared](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/actions/Actions.java;l=59;drc=146d51aa1ec9dcb721a7483479ef0b1ac21d39f1)
between configured targets.
In the execution phase, those shared actions are
[simply considered as one](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/actions/Actions.java;l=241;drc=003b8734036a07b496012730964ac220f486b61f) and only executed once.
However, aquery operates on the pre-execution, post-analysis action graph, and hence treats these
like separate actions whose output Artifacts have the exact same `execPath`. As a result,
equivalent Artifacts appear duplicated.
### Tree artifacts are not expanded
The contents of a [tree artifact](/rules/lib/builtins/actions#declare_directory) are
only known once the action generating it has executed. Since aquery operates on the
pre-execution, post-analysis action graph, it cannot expand a tree artifact into the
individual files it contains.
A tree artifact therefore appears as a single entry holding the path of the directory,
both in an action's inputs and in its command line. This is why the command line reported
by aquery can differ from the parameter file written during the build: the latter is
produced at execution time, when the contents of the directory are known. For example, a
C++ link action may report
```
-Wl,--start-lib \
bazel-out/k8-fastbuild/bin/pkg/_objs/lib/lib_cc \
-Wl,--end-lib
```
where the parameter file on disk lists each `.o` file inside `lib_cc` individually.
To tell a directory apart from a regular file, check the `is_tree_artifact` field on the
`Artifact` message in any of the proto output formats. In `--output=text`, tree artifacts
are suffixed with `(TreeArtifact)`.
The list of aquery issues/planned features can be found on
[GitHub](https://github.com/bazelbuild/bazel/labels/team-Performance).
## FAQs
### The ActionKey remains the same even though the content of an input file changed.
In the context of aquery, the `ActionKey` refers to the `String` gotten from
[ActionAnalysisMetadata#getKey](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/actions/ActionAnalysisMetadata.java;l=89;drc=8b856f5484f0117b2aebc302f849c2a15f273310):
```
Returns a string encoding all of the significant behaviour of this Action that might affect the
output. The general contract of `getKey` is this: if the work to be performed by the
execution of this action changes, the key must change.
...
Examples of changes that should affect the key are:
- Changes to the BUILD file that materially affect the rule which gave rise to this Action.
- Changes to the command-line options, environment, or other global configuration resources
which affect the behaviour of this kind of Action (other than changes to the names of the
input/output files, which are handled externally).
- An upgrade to the build tools which changes the program logic of this kind of Action
(typically this is achieved by incorporating a UUID into the key, which is changed each
time the program logic of this action changes).
Note the following exception: for actions that discover inputs, the key must change if any
input names change or else action validation may falsely validate.
```
This excludes the changes to the content of the input files, and is not to be confused with
[RemoteCacheClient#ActionKey](https://source.bazel.build/bazel/+/master:src/main/java/com/google/devtools/build/lib/remote/common/RemoteCacheClient.java;l=38;drc=21577f202eb90ce94a337ebd2ede824d609537b6).
## Updates
For any issues/feature requests, please file an issue [here](https://github.com/bazelbuild/bazel/issues/new).
# Configurable Query (cquery)
Source: https://bazel.build/query/cquery
`cquery` is a variant of [`query`](/query/language) that correctly handles
[`select()`](/docs/configurable-attributes) and build options' effects on the
build graph.
It achieves this by running over the results of Bazel's [analysis phase](/extending/concepts#evaluation-model),
which integrates these effects. `query`, by contrast, runs over the results of
Bazel's loading phase, before options are evaluated.
For example:
```
$ cat > tree/BUILD <
If this flag is set, its contents are built. *If it's not set, all targets
mentioned in the query expression are built* instead. The transitive closure of
the built targets are used as the universe of the query. Either way, the targets
to be built must be buildable at the top level (that is, compatible with
top-level options). `cquery` returns results in the transitive closure of these
top-level targets.
Even if it's possible to build all targets in a query expression at the top
level, it may be beneficial to not do so. For example, explicitly setting
`--universe_scope` could prevent building targets multiple times in
configurations you don't care about. It could also help specify which
configuration version of a target you're looking for. You should set this flag
if your query expression is more complex than `deps(//foo)`.
#### `--implicit_deps` (boolean, default=True)
Setting this flag to false filters out all results that aren't explicitly set in
the BUILD file and instead set elsewhere by Bazel. This includes filtering
resolved toolchains.
#### `--tool_deps` (boolean, default=True)
Setting this flag to false filters out all configured targets for which the
path from the queried target to them crosses a transition between the target
configuration and the
[non-target configurations](/extending/rules#configurations). If the queried
target is in the target configuration, setting `--notool_deps` will only return
targets that also are in the target configuration. If the queried target is in a
non-target configuration, setting `--notool_deps` will only return targets also
in non-target configurations. This setting generally does not affect filtering
of resolved toolchains.
#### `--include_aspects` (boolean, default=True)
Include dependencies added by [aspects](/extending/aspects).
If this flag is disabled, `cquery somepath(X, Y)` and
`cquery deps(X) | grep 'Y'` omit Y if X only depends on it through an aspect.
## Output formats
By default, cquery outputs results in a dependency-ordered list of label and configuration pairs.
There are other options for exposing the results as well.
### Transitions
```
--transitions=lite
--transitions=full
```
Configuration [transitions](/extending/rules#configurations)
are used to build targets underneath the top level targets in different
configurations than the top level targets.
For example, a target might impose a transition to the exec configuration on all
dependencies in its `tools` attribute. These are known as attribute
transitions. Rules can also impose transitions on their own configurations,
known as rule class transitions. This output format outputs information about
these transitions such as what type they are and the effect they have on build
options.
This output format is triggered by the `--transitions` flag which by default is
set to `NONE`. It can be set to `FULL` or `LITE` mode. `FULL` mode outputs
information about rule class transitions and attribute transitions including a
detailed diff of the options before and after the transition. `LITE` mode
outputs the same information without the options diff.
### Protocol message output
```
--output=proto
```
This option causes the resulting targets to be printed in a binary protocol
buffer form. The definition of the protocol buffer can be found at
[src/main/protobuf/analysis\_v2.proto](https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/analysis_v2.proto).
`CqueryResult` is the top level message containing the results of the cquery. It
has a list of `ConfiguredTarget` messages and a list of `Configuration`
messages. Each `ConfiguredTarget` has a `configuration_id` whose value is equal
to that of the `id` field from the corresponding `Configuration` message.
#### --\[no]proto:include\_configurations
By default, cquery results return configuration information as part of each
configured target. If you'd like to omit this information and get proto output
that is formatted exactly like query's proto output, set this flag to false.
See [query's proto output documentation](/query/language#output-formats)
for more proto output-related options.
Note: While selects are resolved both at the top level of returned
targets and within attributes, all possible inputs for selects are still
included as `rule_input` fields.
### Graph output
```
--output=graph
```
This option generates output as a Graphviz-compatible .dot file. See `query`'s
[graph output documentation](/query/language#display-result-graph) for details. `cquery`
also supports [`--graph:node_limit`](/query/language#graph-nodelimit) and
[`--graph:factored`](/query/language#graph-factored).
### Files output
```
--output=files
```
This option prints a list of the output files produced by each target matched
by the query similar to the list printed at the end of a `bazel build`
invocation. The output contains only the files advertised in the requested
output groups as determined by the
[`--output_groups`](/reference/command-line-reference#flag--output_groups) flag.
It does include source files.
All paths emitted by this output format are relative to the
[execroot](https://bazel.build/remote/output-directories), which can be obtained
via `bazel info execution_root`. If the `bazel-out` convenience symlink exists,
paths to files in the main repository also resolve relative to the workspace
directory.
Note: The output of `bazel cquery --output=files //pkg:foo` contains the output
files of `//pkg:foo` in *all* configurations that occur in the build (also see
the [section on target pattern evaluation](#target-pattern-evaluation)). If that
is not desired, wrap you query in [`config(..., target)`](#config).
### Defining the output format using Starlark
```
--output=starlark
```
This output format calls a [Starlark](/rules/language)
function for each configured target in the query result, and prints the value
returned by the call. The `--starlark:file` flag specifies the location of a
Starlark file that defines a function named `format` with a single parameter,
`target`. This function is called for each [Target](/rules/lib/builtins/Target)
in the query result. Alternatively, for convenience, you may specify just the
body of a function declared as `def format(target): return expr` by using the
`--starlark:expr` flag.
#### 'cquery' Starlark dialect
The cquery Starlark environment differs from a BUILD or .bzl file. It includes
all core Starlark
[built-in constants and functions](https://github.com/bazelbuild/starlark/blob/master/spec.md#built-in-constants-and-functions),
plus a few cquery-specific ones described below, but not (for example) `glob`,
`native`, or `rule`, and it does not support load statements.
##### build\_options(target)
`build_options(target)` returns a map whose keys are build option identifiers
(see [Configurations](/extending/config)) and whose values are their Starlark
values. Build options whose values are not legal Starlark values are omitted
from this map.
If the target is an input file, `build_options(target)` returns None, as input
file targets have a null configuration.
##### providers(target)
`providers(target)` returns a map whose keys are names of
[providers](/extending/rules#providers)
(for example, `"DefaultInfo"`) and whose values are their Starlark values.
Providers whose values are not legal Starlark values are omitted from this map.
#### Examples
Print a space-separated list of the base names of all files produced by `//foo`:
```
bazel cquery //foo --output=starlark \
--starlark:expr="' '.join([f.basename for f in providers(target)['DefaultInfo'].files.to_list()])"
```
Print a space-separated list of the paths of all files produced by **rule** targets in
`//bar` and its subpackages:
```
bazel cquery 'kind(rule, //bar/...)' --output=starlark \
--starlark:expr="' '.join([f.path for f in providers(target)['DefaultInfo'].files.to_list()])"
```
Print a list of the mnemonics of all actions registered by `//foo`.
```
bazel cquery //foo --output=starlark \
--starlark:expr="[a.mnemonic for a in target.actions]"
```
Print a list of compilation outputs registered by a `cc_library` `//baz`.
```
bazel cquery //baz --output=starlark \
--starlark:expr="[f.path for f in target.output_groups.compilation_outputs.to_list()]"
```
Print the value of the command line option `--javacopt` when building `//foo`.
```
bazel cquery //foo --output=starlark \
--starlark:expr="build_options(target)['//command_line_option:javacopt']"
```
Print the label of each target with exactly one output. This example uses
Starlark functions defined in a file.
```
$ cat example.cquery
def has_one_output(target):
return len(providers(target)["DefaultInfo"].files.to_list()) == 1
def format(target):
if has_one_output(target):
return target.label
else:
return ""
$ bazel cquery //baz --output=starlark --starlark:file=example.cquery
```
Print the label of each target which is strictly Python 3. This example uses
Starlark functions defined in a file.
```
$ cat example.cquery
def format(target):
p = providers(target)
py_info = p.get("PyInfo")
if py_info and py_info.has_py3_only_sources:
return target.label
else:
return ""
$ bazel cquery //baz --output=starlark --starlark:file=example.cquery
```
Extract a value from a user defined Provider.
```
$ cat some_package/my_rule.bzl
MyRuleInfo = provider(fields={"color": "the name of a color"})
def _my_rule_impl(ctx):
...
return [MyRuleInfo(color="red")]
my_rule = rule(
implementation = _my_rule_impl,
attrs = {...},
)
$ cat example.cquery
def format(target):
p = providers(target)
my_rule_info = p.get("//some_package:my_rule.bzl%MyRuleInfo'")
if my_rule_info:
return my_rule_info.color
return ""
$ bazel cquery //baz --output=starlark --starlark:file=example.cquery
```
## cquery vs. query
`cquery` and `query` complement each other and excel in
different niches. Consider the following to decide which is right for you:
* `cquery` follows specific `select()` branches to
model the exact graph you build. `query` doesn't know which
branch the build chooses, so overapproximates by including all branches.
* `cquery`'s precision requires building more of the graph than
`query` does. Specifically, `cquery`
evaluates *configured targets* while `query` only
evaluates *targets*. This takes more time and uses more memory.
* `cquery`'s interpretation of
the [query language](/query/language) introduces ambiguity
that `query` avoids. For example,
if `"//foo"` exists in two configurations, which one
should `cquery "deps(//foo)"` use?
The [`config`](#config) function can help with this.
## Non-deterministic output
`cquery` does not automatically wipe the build graph from previous commands.
It's therefore prone to picking up results from past queries.
For example, `genrule` exerts an exec transition on its `tools` attribute -
that is, it configures its tools in the [exec configuration](https://bazel.build/rules/rules#configurations).
You can see the lingering effects of that transition below.
```
$ cat > foo/BUILD <<" to "//:*", piped into a "+"-delimited line merge.
# Output looks like "//foo:*+//foo/bar:*+//foo/baz".
#
$ bazel cquery --universe_scope=//foo:app "somepath(//foo:app, $(bazel query //foo/...
--output=package | sed -e 's/^/\/\//' -e 's/$/:*/' | paste -sd "+" -))"
```
# Be nav
Source: https://bazel.build/reference/be/be-nav
\*\*Build Encyclopedia\*\*
* [Overview](/reference/be/overview)
* [Concepts](#be-menu)
* [Common Definitions](/reference/be/common-definitions)
* ["Make" variables](/reference/be/make-variables)
* [Rules](#be-rules)
* [Functions](/reference/be/functions)
* [C / C++](/reference/be/c-cpp)
* [Java](/reference/be/java)
* [Objective-C](/reference/be/objective-c)
* [Protocol Buffer](/reference/be/protocol-buffer)
* [Python](/reference/be/python)
* [Shell](/reference/be/shell)
* [Extra Actions](/reference/be/extra-actions)
* [General](/reference/be/general)
* [Platforms and Toolchains](/reference/be/platforms-and-toolchains)
* [AppEngine](https://github.com/bazelbuild/rules_appengine)
* [Apple (Swift, iOS, macOS, tvOS, visionOS, watchOS)](https://github.com/bazelbuild/rules_apple)
* [C#](https://github.com/bazelbuild/rules_dotnet)
* [D](https://github.com/bazelbuild/rules_d)
* [Docker](https://github.com/bazelbuild/rules_docker)
* [Groovy](https://github.com/bazelbuild/rules_groovy)
* [Go](https://github.com/bazelbuild/rules_go)
* [JavaScript (Closure)](https://github.com/bazelbuild/rules_closure)
* [Jsonnet](https://github.com/bazelbuild/rules_jsonnet)
* [Packaging](/reference/be/pkg)
* [Rust](https://github.com/bazelbuild/rules_rust)
* [Sass](https://github.com/bazelbuild/rules_sass)
* [Scala](https://github.com/bazelbuild/rules_scala)
# C / C++ Rules
Source: https://bazel.build/reference/be/c-cpp
## Rules
* [cc\_binary](#cc_binary)
* [cc\_import](#cc_import)
* [cc\_library](#cc_library)
* [cc\_shared\_library](#cc_shared_library)
* [cc\_static\_library](#cc_static_library)
* [cc\_test](#cc_test)
* [cc\_toolchain](#cc_toolchain)
* [fdo\_prefetch\_hints](#fdo_prefetch_hints)
* [fdo\_profile](#fdo_profile)
* [memprof\_profile](#memprof_profile)
* [propeller\_optimize](#propeller_optimize)
## cc\_binary
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/cc_binary.bzl)
```
cc_binary(name, deps, srcs, data, additional_compiler_inputs, additional_linker_inputs, args, aspect_hints, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, dynamic_deps, env, exec_compatible_with, exec_group_compatible_with, exec_properties, features, hdrs_check, includes, licenses, link_extra_lib, linkopts, linkshared, linkstatic, local_defines, local_includes, malloc, module_interfaces, nocopts, output_licenses, package_metadata, reexport_deps, restricted_to, stamp, tags, target_compatible_with, testonly, toolchains, visibility, win_def_file)
```
It produces an executable binary.
The `name` of the target should be the same as the name of the
source file that is the main entry point of the application (minus the extension).
For example, if your entry point is in `main.cc`, then your name should
be `main`.
#### Implicit output targets
* `name.stripped` (only built if explicitly requested): A stripped
version of the binary. `strip -g` is run on the binary to remove debug
symbols. Additional strip options can be provided on the command line using
`--stripopt=-foo`.
* `name.dwp` (only built if explicitly requested): If
[Fission](https://gcc.gnu.org/wiki/DebugFission) is enabled: a debug
information package file suitable for debugging remotely deployed binaries. Else: an
empty file.
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries to be linked in to the binary target. These can be `cc_library` or `objc_library` targets. It is also allowed to put linker scripts (.lds) into deps, and reference them in [`linkopts`](#cc_binary.linkopts), but please consider [`additional_linker_inputs`](#cc_binary.additional_linker_inputs) for that use case. |
| `srcs` |
The list of C and C++ files that are processed to create the library target. These are C/C++ source and header files, either non-generated (normal source code) or generated.
All `.cc`, `.c`, and `.cpp` files will be compiled. These might be generated files: if a named file is in the `outs` of some other rule, this `cc_library` will automatically depend on that other rule.
Pure assembler files (.s, .asm) are not preprocessed and are typically built using the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built using the C/C++ compiler.
A `.h` file will not be compiled, but will be available for inclusion by sources in this rule. Both `.cc` and `.h` files can directly include headers listed in these `srcs` or in the `hdrs` of this rule or any rule listed in the `deps` argument.
All `#include`d files must be mentioned in the `hdrs` attribute of this or referenced `cc_library` rules, or they should be listed in `srcs` if they are private to this library. See "Header inclusion checking" for a more detailed description.
`.so`, `.lo`, and `.a` files are pre-compiled files. Your library might have these as `srcs` if it uses third-party code for which we don't have source code.
If the `srcs` attribute includes the label of another rule, `cc_library` will use the output files of that rule as source files to compile. This is useful for one-off generation of source code (for more than occasional use, it's better to implement a Starlark rule class and use the `cc_common` API)
Permitted `srcs` file types:
C and C++ source files: `.c`, `.cc`, `.cpp`, `.cxx`, `.c++`, `.C`
C and C++ header files: `.h`, `.hh`, `.hpp`, `.hxx`, `.inc`, `.inl`, `.H`
Assembler with C preprocessor: `.S`
Archive: `.a`, `.pic.a`
"Always link" library: `.lo`, `.pic.lo`
Shared library, versioned or unversioned: `.so`, `.so.version`
Object file: `.o`, `.pic.o`
... and any rules that produce those files (e.g. `cc_embed_data`). Different extensions denote different programming languages in accordance with gcc convention.
If a `data` is the name of a generated file, then this `cc_library` rule automatically depends on the generating rule.
If a `data` is a rule name, then this `cc_library` rule automatically depends on that rule, and that rule's `outs` are automatically added to this `cc_library`'s data files.
Your C++ code can access these data files like so:
`const std::string path = devtools_build::GetDataDependencyFilepath( "my/test/data/file");` |
| `additional_compiler_inputs` | List of [labels](/concepts/labels); default is `[]` Any additional files you might want to pass to the compiler command line, such as sanitizer ignorelists, for example. Files specified here can then be used in copts with the \$(location) function. |
| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Dependencies that are only made available to the C++ linker command. Unlike `deps`, which is conceptually made for both compilation and linking dependencies, `additional_linker_inputs` is specifically made for only the latter, and signals a dependency that is required only for linking (for example, files that are referenced in `linkopts`). For example, compiled Windows .res files can be provided here to be embedded in the binary target. |
| `conlyopts` | List of strings; default is `[]` Add these options to the C compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). |
| `copts` | List of strings; default is `[]` Add these options to the C/C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string in this attribute is added in the given order to `COPTS` before compiling the binary target. The flags take effect only for compiling this target, not its dependencies, so be careful about header files included elsewhere. All paths should be relative to the workspace, not to the current package. This attribute should not be needed outside of `third_party`. If the package declares the [feature](/reference/be/functions#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings that consist of a single "Make" variable. |
| `cxxopts` | List of strings; default is `[]` Add these options to the C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). |
| `defines` | List of strings; default is `[]` List of defines to add to the compile line of this and all dependent targets. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line to this target, as well as to every rule that depends on it. Be very careful, since this may have far-reaching effects -- the defines are added to every target that depends on this target. When in doubt, add define values to [`local_defines`](#cc_binary.local_defines) instead. |
| `dynamic_deps` | List of [labels](/concepts/labels); default is `[]` These are other `cc_shared_library` dependencies the current target depends on. The `cc_shared_library` implementation will use the list of `dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the current target's `dynamic_deps`) to decide which `cc_libraries` in the transitive `deps` should not be linked in because they are already provided by a different `cc_shared_library`. |
| `hdrs_check` | String; default is `""` Deprecated, no-op. |
| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-I path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When the include path is only needed to compile this target, use [`local_includes`](#cc_binary.local_includes) instead. The added `include` paths will include generated files as well as files in the source tree. |
| `link_extra_lib` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:link_extra_lib"` Control linking of extra libraries. By default, C++ binaries are linked against `@bazel_tools//tools/cpp:link_extra_lib`, which by default depends on the label flag `@bazel_tools//tools/cpp:link_extra_libs`. Without setting the flag, this library is empty by default. Setting the label flag allows linking optional dependencies, such as overrides for weak symbols, interceptors for shared library functions, or special runtime libraries (for malloc replacements, prefer `malloc` or `--custom_malloc`). Setting this attribute to `None` disables this behaviour. |
| `linkopts` | List of strings; default is `[]` Add these flags to the C++ linker command. Subject to ["Make" variable](make-variables) substitution, [Bourne shell tokenization](common-definitions#sh-tokenization) and [label expansion](common-definitions#label-expansion). Each string in this attribute is added to `LINKOPTS` before linking the binary target. Each element of this list that does not start with `$` or `-` is assumed to be the label of a target in `deps`. The list of files generated by that target is appended to the linker options. An error is reported if the label is invalid, or is not declared in `deps`. |
| `linkshared` | Boolean; default is `False` Create a shared library. To enable this attribute, include `linkshared=True` in your rule. By default this option is off. The presence of this flag means that linking occurs with the `-shared` flag to `gcc`, and the resulting shared library is suitable for loading into for example a Java program. However, for build purposes it will never be linked into the dependent binary, as it is assumed that shared libraries built with a [cc\_binary](#cc_binary) rule are only loaded manually by other programs, so it should not be considered a substitute for the [cc\_library](#cc_library) rule. For sake of scalability we recommend avoiding this approach altogether and simply letting `java_library` depend on `cc_library` rules instead. If you specify both `linkopts=['-static']` and `linkshared=True`, you get a single completely self-contained unit. If you specify both `linkstatic=True` and `linkshared=True`, you get a single, mostly self-contained unit. |
| `linkstatic` |
Boolean; default is `True`
For `cc_binary` and `cc_test`: link the binary in static mode. For `cc_library.link_static`: see below.
By default this option is on for `cc_binary` and off for the rest.
If enabled and this is a binary or test, this option tells the build tool to link in `.a`'s instead of `.so`'s for user libraries whenever possible. System libraries such as libc (but not the C/C++ runtime libraries, see below) are still linked dynamically, as are libraries for which there is no static library. So the resulting executable will still be dynamically linked, hence only mostly static.
There are really three different ways to link an executable:
STATIC with fully\_static\_link feature, in which everything is linked statically; e.g. "`gcc -static foo.o libbar.a libbaz.a -lm`". This mode is enabled by specifying `fully_static_link` in the `features` attribute.
STATIC, in which all user libraries are linked statically (if a static version is available), but where system libraries (excluding C/C++ runtime libraries) are linked dynamically, e.g. "`gcc foo.o libfoo.a libbaz.a -lm`". This mode is enabled by specifying `linkstatic=True`.
DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is available), e.g. "`gcc foo.o libfoo.so libbaz.so -lm`". This mode is enabled by specifying `linkstatic=False`.
If the `linkstatic` attribute or `fully_static_link` in `features` is used outside of `//third_party` please include a comment near the rule to explain why.
The `linkstatic` attribute has a different meaning if used on a `cc_library()` rule. For a C++ library, `linkstatic=True` indicates that only static linking is allowed, so no `.so` will be produced. linkstatic=False does not prevent static libraries from being created. The attribute is meant to control the creation of dynamic libraries.
There should be very little code built with `linkstatic=False` in production. If `linkstatic=False`, then the build tool will create symlinks to depended-upon shared libraries in the `*.runfiles` area.
|
| `local_defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line for this target, but not to its dependents. Unlike `defines`, the defines are only added to the compile command line for this target. |
| `local_includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-I path_to_package/local_include_entry`. Unlike [INCLUDES](#cc_binary.includes), these flags are added for this target and not added to every target that depends on it. The `local_includes` paths will include generated files as well as files in the source tree. |
| `malloc` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:malloc"` Override the default dependency on malloc. By default, C++ binaries are linked against `//tools/cpp:malloc`, which is an empty library so the binary ends up using libc malloc. This label must refer to a `cc_library`. If compilation is for a non-C++ rule, this option has no effect. The value of this attribute is ignored if `linkshared=True` is specified. |
| `module_interfaces` |
The list of files are regarded as C++20 Modules Interface.
C++ Standard has no restriction about module interface file extension
Clang use cppm
GCC can use any source file extension
MSVC use ixx
The use is guarded by the flag `--experimental_cpp_modules`.
|
| `nocopts` | String; default is `""` Deprecated, no-op. |
| `reexport_deps` | List of [labels](/concepts/labels); default is `[]` |
| `stamp` |
Integer; default is `-1`
Whether to encode build information into the binary. Possible values:
`stamp = 1`: Always stamp the build information into the binary, even in `--nostamp` builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
`stamp = 0`: Always replace build information by constant values. This gives good build result caching.
`stamp = -1`: Embedding of build information is controlled by the `--[no]stamp` flag.
Stamped binaries are not rebuilt unless their dependencies change.
|
| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. |
## cc\_import
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/cc_import.bzl)
```
cc_import(name, deps, data, hdrs, alwayslink, aspect_hints, compatible_with, defines, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, includes, interface_library, linkopts, objects, package_metadata, pic_objects, pic_static_library, restricted_to, shared_library, static_library, strip_include_prefix, system_provided, tags, target_compatible_with, testonly, toolchains, visibility)
```
`cc_import` rules allows users to import precompiled C/C++ libraries.
The following are the typical use cases:
1. Linking a static library
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
static_library = "libmylib.a",
# If alwayslink is turned on,
# libmylib.a will be forcely linked into any binary that depends on it.
# alwayslink = True,
)
```
2. Linking a shared library (Unix)
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
shared_library = "libmylib.so",
)
```
3. Linking a shared library with interface library
On Unix:
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
# libmylib.ifso is an interface library for libmylib.so which will be passed to linker
interface_library = "libmylib.ifso",
# libmylib.so will be available for runtime
shared_library = "libmylib.so",
)
```
On Windows:
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
# mylib.lib is an import library for mylib.dll which will be passed to linker
interface_library = "mylib.lib",
# mylib.dll will be available for runtime
shared_library = "mylib.dll",
)
```
4. Linking a shared library with `system_provided=True`
On Unix:
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
interface_library = "libmylib.ifso", # Or we can also use libmylib.so as its own interface library
# libmylib.so is provided by system environment, for example it can be found in LD_LIBRARY_PATH.
# This indicates that Bazel is not responsible for making libmylib.so available.
system_provided = True,
)
```
On Windows:
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
# mylib.lib is an import library for mylib.dll which will be passed to linker
interface_library = "mylib.lib",
# mylib.dll is provided by system environment, for example it can be found in PATH.
# This indicates that Bazel is not responsible for making mylib.dll available.
system_provided = True,
)
```
5. Linking to static or shared library
On Unix:
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
static_library = "libmylib.a",
shared_library = "libmylib.so",
)
```
On Windows:
```
cc_import(
name = "mylib",
hdrs = ["mylib.h"],
static_library = "libmylib.lib", # A normal static library
interface_library = "mylib.lib", # An import library for mylib.dll
shared_library = "mylib.dll",
)
```
The remaining is the same on Unix and Windows:
```
# first will link to libmylib.a (or libmylib.lib)
cc_binary(
name = "first",
srcs = ["first.cc"],
deps = [":mylib"],
linkstatic = True, # default value
)
# second will link to libmylib.so (or libmylib.lib)
cc_binary(
name = "second",
srcs = ["second.cc"],
deps = [":mylib"],
linkstatic = False,
)
```
`cc_import` supports an include attribute. For example:
```
cc_import(
name = "curl_lib",
hdrs = glob(["vendor/curl/include/curl/*.h"]),
includes = ["vendor/curl/include"],
shared_library = "vendor/curl/lib/.libs/libcurl.dylib",
)
```
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries that the target depends upon. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). |
| `data` | List of [labels](/concepts/labels); default is `[]` The list of files needed by this library at runtime. See general comments about `data` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). |
| `hdrs` | List of [labels](/concepts/labels); default is `[]` The list of header files published by this precompiled library to be directly included by sources in dependent rules. |
| `alwayslink` | Boolean; default is `False` If enabled, any binary that depends (directly or indirectly) on this C++ precompiled library will link in all the object files archived in the static library, even if some contain no symbols referenced by the binary. This is useful if your code isn't explicitly called by code in the binary, e.g., if your code registers to receive some callback provided by some service. If `alwayslink` doesn't work with VS 2017 on Windows, that is due to a [known issue](https://github.com/bazelbuild/bazel/issues/3949), please upgrade your VS 2017 to the latest version. |
| `defines` | List of strings; default is `[]` List of defines to add to the compile line of this and all dependent targets. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line to this target, as well as to every rule that depends on it. Be very careful, since this may have far-reaching effects -- the defines are added to every target that depends on this target. |
| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-I path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When in doubt, add "-I" flags to [COPTS](#cc_binary.copts) instead. The default `include` path doesn't include generated files. If you need to `#include` a generated header file, list it in the `srcs`. |
| `interface_library` | [Label](/concepts/labels); default is `None` A single interface library for linking the shared library. Permitted file types: `.ifso`, `.tbd`, `.lib`, `.so` or `.dylib` |
| `linkopts` | List of strings; default is `[]` Add these flags to the C++ linker command. Subject to ["Make" variable](make-variables) substitution, [Bourne shell tokenization](common-definitions#sh-tokenization) and [label expansion](common-definitions#label-expansion). Each string in this attribute is added to `LINKOPTS` before linking the binary target. Each element of this list that does not start with `$` or `-` is assumed to be the label of a target in `deps`. The list of files generated by that target is appended to the linker options. An error is reported if the label is invalid, or is not declared in `deps`. |
| `objects` | List of [labels](/concepts/labels); default is `[]` |
| `pic_objects` | List of [labels](/concepts/labels); default is `[]` |
| `pic_static_library` | [Label](/concepts/labels); default is `None` |
| `shared_library` | [Label](/concepts/labels); default is `None` A single precompiled shared library. Bazel ensures it is available to the binary that depends on it during runtime. Permitted file types: `.so`, `.dll` `.dylib`, or `.pyd` |
| `static_library` | [Label](/concepts/labels); default is `None` A single precompiled static library. Permitted file types: `.a`, `.pic.a` or `.lib` |
| `strip_include_prefix` | String; default is `""` The prefix to strip from the paths of the headers of this rule. When set, the headers in the `hdrs` attribute of this rule are accessible at their path with this prefix cut off. If it's a relative path, it's taken as a package-relative one. If it's an absolute one, it's understood as a repository-relative path. The prefix in the `include_prefix` attribute is added after this prefix is stripped. This attribute is only legal under `third_party`. |
| `system_provided` | Boolean; default is `False` If enabled, it indicates the shared library required at runtime is provided by the system. In this case, `interface_library` should be specified and `shared_library` should be empty. |
## cc\_library
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/cc_library.bzl)
```
cc_library(name, deps, srcs, data, hdrs, additional_compiler_inputs, additional_linker_inputs, alwayslink, aspect_hints, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, hdrs_check, implementation_deps, include_prefix, includes, licenses, linkopts, linkstamp, linkstatic, local_defines, local_includes, module_interfaces, package_metadata, restricted_to, strip_include_prefix, tags, target_compatible_with, testonly, textual_hdrs, toolchains, visibility, win_def_file)
```
Use `cc_library()` for C++-compiled libraries.
The result is either a `.so`, `.lo`,
or `.a`, depending on what is needed.
If you build something with static linking that depends on
a `cc_library`, the output of a depended-on library rule
is the `.a` file. If you specify
`alwayslink=True`, you get the `.lo` file.
The actual output file name is `libfoo.so` for
the shared library, where *foo* is the name of the rule. The
other kinds of libraries end with `.lo` and `.a`,
respectively. If you need a specific shared library name, for
example, to define a Python module, use a genrule to copy the library
to the desired name.
#### Header inclusion checking
All header files that are used in the build must be declared in
the `hdrs` or `srcs` of `cc_*` rules.
This is enforced.
For `cc_library` rules, headers in `hdrs` comprise the
public interface of the library and can be directly included both
from the files in `hdrs` and `srcs` of the library
itself as well as from files in `hdrs` and `srcs`
of `cc_*` rules that list the library in their `deps`.
Headers in `srcs` must only be directly included from the files
in `hdrs` and `srcs` of the library itself. When
deciding whether to put a header into `hdrs` or `srcs`,
you should ask whether you want consumers of this library to be able to
directly include it. This is roughly the same decision as
between `public` and `private` visibility in programming languages.
`cc_binary` and `cc_test` rules do not have an exported
interface, so they also do not have a `hdrs` attribute. All headers
that belong to the binary or test directly should be listed in
the `srcs`.
To illustrate these rules, look at the following example.
```
cc_binary(
name = "foo",
srcs = [
"foo.cc",
"foo.h",
],
deps = [":bar"],
)
cc_library(
name = "bar",
srcs = [
"bar.cc",
"bar-impl.h",
],
hdrs = ["bar.h"],
deps = [":baz"],
)
cc_library(
name = "baz",
srcs = [
"baz.cc",
"baz-impl.h",
],
hdrs = ["baz.h"],
)
```
The allowed direct inclusions in this example are listed in the table below.
For example `foo.cc` is allowed to directly
include `foo.h` and `bar.h`, but not `baz.h`.
| Including file | Allowed inclusions |
| - | - |
| foo.h | bar.h |
| foo.cc | foo.h bar.h |
| bar.h | bar-impl.h baz.h |
| bar-impl.h | bar.h baz.h |
| bar.cc | bar.h bar-impl.h baz.h |
| baz.h | baz-impl.h |
| baz-impl.h | baz.h |
| baz.cc | baz.h baz-impl.h |
The inclusion checking rules only apply to *direct*
inclusions. In the example above `foo.cc` is allowed to
include `bar.h`, which may include `baz.h`, which in
turn is allowed to include `baz-impl.h`. Technically, the
compilation of a `.cc` file may transitively include any header
file in the `hdrs` or `srcs` in
any `cc_library` in the transitive `deps` closure. In
this case the compiler may read `baz.h` and `baz-impl.h`
when compiling `foo.cc`, but `foo.cc` must not
contain `#include "baz.h"`. For that to be
allowed, `baz` must be added to the `deps`
of `foo`.
Bazel depends on toolchain support to enforce the inclusion checking rules.
The `layering_check` feature has to be supported by the toolchain
and requested explicitly, for example via the
`--features=layering_check` command-line flag or the
`features` parameter of the
[`package`](/reference/be/functions#package) function. The toolchains
provided by Bazel only support this feature with clang on Unix and macOS.
#### Examples
We use the `alwayslink` flag to force the linker to link in
this code although the main binary code doesn't reference it.
```
cc_library(
name = "ast_inspector_lib",
srcs = ["ast_inspector_lib.cc"],
hdrs = ["ast_inspector_lib.h"],
visibility = ["//visibility:public"],
deps = ["//third_party/llvm/llvm/tools/clang:frontend"],
# alwayslink as we want to be able to call things in this library at
# debug time, even if they aren't used anywhere in the code.
alwayslink = True,
)
```
The following example comes from
`third_party/python2_4_3/BUILD`.
Some of the code uses the `dl` library (to load
another, dynamic library), so this
rule specifies the `-ldl` link option to link the
`dl` library.
```
cc_library(
name = "python2_4_3",
linkopts = [
"-ldl",
"-lutil",
],
deps = ["//third_party/expat"],
)
```
The following example comes from `third_party/kde/BUILD`.
We keep pre-built `.so` files in the depot.
The header files live in a subdirectory named `include`.
```
cc_library(
name = "kde",
srcs = [
"lib/libDCOP.so",
"lib/libkdesu.so",
"lib/libkhtml.so",
"lib/libkparts.so",
...more .so files...,
],
includes = ["include"],
deps = ["//third_party/X11"],
)
```
The following example comes from `third_party/gles/BUILD`.
Third-party code often needs some `defines` and
`linkopts`.
```
cc_library(
name = "gles",
srcs = [
"GLES/egl.h",
"GLES/gl.h",
"ddx.c",
"egl.c",
],
defines = [
"USE_FLOAT",
"__GL_FLOAT",
"__GL_COMMON",
],
linkopts = ["-ldl"], # uses dlopen(), dl library
deps = [
"es",
"//third_party/X11",
],
)
```
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries that the library target depends upon. These can be `cc_library` or `objc_library` targets. See general comments about `deps` at [Typical attributes defined by most build rules](/reference/be/common-definitions#typical-attributes). These should be names of C++ library rules. When you build a binary that links this rule's library, you will also link the libraries in `deps`. Despite the "deps" name, not all of this library's clients belong here. Run-time data dependencies belong in `data`. Source files generated by other rules belong in `srcs`. To link in a pre-compiled third-party library, add its name to the `srcs` instead. To depend on something without linking it to this library, add its name to the `data` instead. |
| `srcs` |
The list of C and C++ files that are processed to create the library target. These are C/C++ source and header files, either non-generated (normal source code) or generated.
All `.cc`, `.c`, and `.cpp` files will be compiled. These might be generated files: if a named file is in the `outs` of some other rule, this `cc_library` will automatically depend on that other rule.
Pure assembler files (.s, .asm) are not preprocessed and are typically built using the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built using the C/C++ compiler.
A `.h` file will not be compiled, but will be available for inclusion by sources in this rule. Both `.cc` and `.h` files can directly include headers listed in these `srcs` or in the `hdrs` of this rule or any rule listed in the `deps` argument.
All `#include`d files must be mentioned in the `hdrs` attribute of this or referenced `cc_library` rules, or they should be listed in `srcs` if they are private to this library. See "Header inclusion checking" for a more detailed description.
`.so`, `.lo`, and `.a` files are pre-compiled files. Your library might have these as `srcs` if it uses third-party code for which we don't have source code.
If the `srcs` attribute includes the label of another rule, `cc_library` will use the output files of that rule as source files to compile. This is useful for one-off generation of source code (for more than occasional use, it's better to implement a Starlark rule class and use the `cc_common` API)
Permitted `srcs` file types:
C and C++ source files: `.c`, `.cc`, `.cpp`, `.cxx`, `.c++`, `.C`
C and C++ header files: `.h`, `.hh`, `.hpp`, `.hxx`, `.inc`, `.inl`, `.H`
Assembler with C preprocessor: `.S`
Archive: `.a`, `.pic.a`
"Always link" library: `.lo`, `.pic.lo`
Shared library, versioned or unversioned: `.so`, `.so.version`
Object file: `.o`, `.pic.o`
... and any rules that produce those files (e.g. `cc_embed_data`). Different extensions denote different programming languages in accordance with gcc convention.
If a `data` is the name of a generated file, then this `cc_library` rule automatically depends on the generating rule.
If a `data` is a rule name, then this `cc_library` rule automatically depends on that rule, and that rule's `outs` are automatically added to this `cc_library`'s data files.
Your C++ code can access these data files like so:
`const std::string path = devtools_build::GetDataDependencyFilepath( "my/test/data/file");` |
| `hdrs` | List of [labels](/concepts/labels); default is `[]` The list of header files published by this library to be directly included by sources in dependent rules. This is the strongly preferred location for declaring header files that describe the interface for the library. These headers will be made available for inclusion by sources in this rule or in dependent rules. Headers not meant to be included by a client of this library should be listed in the `srcs` attribute instead, even if they are included by a published header. See ["Header inclusion checking"](#hdrs) for a more detailed description. Permitted `headers` file types: `.h`, `.hh`, `.hpp`, `.hxx`. |
| `additional_compiler_inputs` | List of [labels](/concepts/labels); default is `[]` Any additional files you might want to pass to the compiler command line, such as sanitizer ignorelists, for example. Files specified here can then be used in copts with the \$(location) function. |
| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Dependencies that are only made available to the C++ linker command. Unlike `deps`, which is conceptually made for both compilation and linking dependencies, `additional_linker_inputs` is specifically made for only the latter, and signals a dependency that is required only for linking (for example, files that are referenced in `linkopts`). For example, compiled Windows .res files can be provided here to be embedded in the binary target. |
| `alwayslink` | Boolean; default is `False` If 1, any binary that depends (directly or indirectly) on this C++ library will link in all the object files for the files listed in `srcs`, even if some contain no symbols referenced by the binary. This is useful if your code isn't explicitly called by code in the binary, e.g., if your code registers to receive some callback provided by some service. If alwayslink doesn't work with VS 2017 on Windows, that is due to a [known issue](https://github.com/bazelbuild/bazel/issues/3949), please upgrade your VS 2017 to the latest version. |
| `conlyopts` | List of strings; default is `[]` Add these options to the C compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). |
| `copts` | List of strings; default is `[]` Add these options to the C/C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string in this attribute is added in the given order to `COPTS` before compiling the binary target. The flags take effect only for compiling this target, not its dependencies, so be careful about header files included elsewhere. All paths should be relative to the workspace, not to the current package. This attribute should not be needed outside of `third_party`. If the package declares the [feature](/reference/be/functions#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings that consist of a single "Make" variable. |
| `cxxopts` | List of strings; default is `[]` Add these options to the C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). |
| `defines` | List of strings; default is `[]` List of defines to add to the compile line of this and all dependent targets. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line to this target, as well as to every rule that depends on it. Be very careful, since this may have far-reaching effects -- the defines are added to every target that depends on this target. When in doubt, add define values to [`local_defines`](#cc_binary.local_defines) instead. |
| `hdrs_check` | String; default is `""` Deprecated, no-op. |
| `implementation_deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries that the library target depends on. Unlike with `deps`, the headers and include paths of these libraries (and all their transitive deps) are only used for compilation of this library, and not libraries that depend on it. Libraries specified with `implementation_deps` are still linked in binary targets that depend on this library. |
| `include_prefix` | String; default is `""` The prefix to add to the paths of the headers of this rule. When set, the headers in the `hdrs` attribute of this rule are accessible at a path formed by prepending this attribute's value to their repository-relative path. For example, if a library in package `foo` sets `include_prefix = "mylib"` and has `bar.h` in `hdrs`, dependent rules would include it as `#include "mylib/bar.h"` instead of `#include "foo/bar.h"`. The prefix in the `strip_include_prefix` attribute is removed before this prefix is added. This attribute is only legal under `third_party`. |
| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-I path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When the include path is only needed to compile this target, use [`local_includes`](#cc_binary.local_includes) instead. The added `include` paths will include generated files as well as files in the source tree. |
| `linkopts` | List of strings; default is `[]` See [`cc_binary.linkopts`](/reference/be/c-cpp#cc_binary.linkopts). The `linkopts` attribute is also applied to any target that depends, directly or indirectly, on this library via `deps` attributes (or via other attributes that are treated similarly: the [`malloc`](/reference/be/c-cpp#cc_binary.malloc) attribute of [`cc_binary`](/reference/be/c-cpp#cc_binary)). Dependency linkopts take precedence over dependent linkopts (i.e. dependency linkopts appear later in the command line). Linkopts specified in [`--linkopt`](../user-manual#flag--linkopt) take precedence over rule linkopts. |
Note that the `linkopts` attribute only applies
when creating `.so` files or executables, not
when creating `.a` or `.lo` files.
So if the `linkstatic=True` attribute is set, the
`linkopts` attribute has no effect on the creation of
this library, only on other targets which depend on this library.
Also, it is important to note that "-Wl,-soname" or "-Xlinker -soname"
options are not supported and should never be specified in this attribute.
The `.so` files produced by `cc_library`
rules are not linked against the libraries that they depend
on. If you're trying to create a shared library for use
outside of the main repository, e.g. for manual use
with `dlopen()` or `LD_PRELOAD`,
it may be better to use a `cc_binary` rule
with the `linkshared=True` attribute.
See [`cc_binary.linkshared`](/reference/be/c-cpp#cc_binary.linkshared).
\| `linkstamp` | [Label](/concepts/labels); default is `None` Simultaneously compiles and links the specified C++ source file into the final binary. This trickery is required to introduce timestamp information into binaries; if we compiled the source file to an object file in the usual way, the timestamp would be incorrect. A linkstamp compilation may not include any particular set of compiler flags and so should not depend on any particular header, compiler option, or other build variable. *This option should only be needed in the `base` package.* |
\| `linkstatic` |
Boolean; default is `False`
For `cc_binary` and `cc_test`: link the binary in static mode. For `cc_library.link_static`: see below.
By default this option is on for `cc_binary` and off for the rest.
If enabled and this is a binary or test, this option tells the build tool to link in `.a`'s instead of `.so`'s for user libraries whenever possible. System libraries such as libc (but not the C/C++ runtime libraries, see below) are still linked dynamically, as are libraries for which there is no static library. So the resulting executable will still be dynamically linked, hence only mostly static.
There are really three different ways to link an executable:
STATIC with fully\_static\_link feature, in which everything is linked statically; e.g. "`gcc -static foo.o libbar.a libbaz.a -lm`". This mode is enabled by specifying `fully_static_link` in the `features` attribute.
STATIC, in which all user libraries are linked statically (if a static version is available), but where system libraries (excluding C/C++ runtime libraries) are linked dynamically, e.g. "`gcc foo.o libfoo.a libbaz.a -lm`". This mode is enabled by specifying `linkstatic=True`.
DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is available), e.g. "`gcc foo.o libfoo.so libbaz.so -lm`". This mode is enabled by specifying `linkstatic=False`.
If the `linkstatic` attribute or `fully_static_link` in `features` is used outside of `//third_party` please include a comment near the rule to explain why.
The `linkstatic` attribute has a different meaning if used on a `cc_library()` rule. For a C++ library, `linkstatic=True` indicates that only static linking is allowed, so no `.so` will be produced. linkstatic=False does not prevent static libraries from being created. The attribute is meant to control the creation of dynamic libraries.
There should be very little code built with `linkstatic=False` in production. If `linkstatic=False`, then the build tool will create symlinks to depended-upon shared libraries in the `*.runfiles` area.
|
\| `local_defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line for this target, but not to its dependents. Unlike `defines`, the defines are only added to the compile command line for this target. |
\| `local_includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-I path_to_package/local_include_entry`. Unlike [INCLUDES](#cc_binary.includes), these flags are added for this target and not added to every target that depends on it. The `local_includes` paths will include generated files as well as files in the source tree. |
\| `module_interfaces` |
The list of files are regarded as C++20 Modules Interface.
C++ Standard has no restriction about module interface file extension
Clang use cppm
GCC can use any source file extension
MSVC use ixx
The use is guarded by the flag `--experimental_cpp_modules`.
|
\| `strip_include_prefix` | String; default is `""` The prefix to strip from the paths of the headers of this rule. When set, the headers in the `hdrs` attribute of this rule are accessible at their path with this prefix cut off. If it's a relative path, it's taken as a package-relative one. If it's an absolute one, it's understood as a repository-relative path. The prefix in the `include_prefix` attribute is added after this prefix is stripped. This attribute is only legal under `third_party`. |
\| `textual_hdrs` | List of [labels](/concepts/labels); default is `[]` The list of header files published by this library to be textually included by sources in dependent rules. This is the location for declaring header files that cannot be compiled on their own; that is, they always need to be textually included by other source files to build valid code. |
\| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. |
## cc\_shared\_library
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/cc_shared_library.bzl)
```
cc_shared_library(name, deps, additional_linker_inputs, aspect_hints, compatible_with, deprecation, dynamic_deps, exec_compatible_with, exec_group_compatible_with, exec_properties, exports_filter, features, package_metadata, restricted_to, roots, shared_lib_name, static_deps, tags, target_compatible_with, testonly, toolchains, user_link_flags, visibility, win_def_file)
```
It produces a shared library.
#### Example
```
cc_shared_library(
name = "foo_shared",
deps = [
":foo",
],
dynamic_deps = [
":bar_shared",
],
additional_linker_inputs = [
":foo.lds",
],
user_link_flags = [
"-Wl,--version-script=$(location :foo.lds)",
],
)
cc_library(
name = "foo",
srcs = ["foo.cc"],
hdrs = ["foo.h"],
deps = [
":bar",
":baz",
],
)
cc_shared_library(
name = "bar_shared",
shared_lib_name = "bar.so",
deps = [":bar"],
)
cc_library(
name = "bar",
srcs = ["bar.cc"],
hdrs = ["bar.h"],
)
cc_library(
name = "baz",
srcs = ["baz.cc"],
hdrs = ["baz.h"],
)
```
In the example `foo_shared` statically links `foo`
and `baz`, the latter being a transitive dependency. It doesn't
link `bar` because it is already provided dynamically by the
`dynamic_dep` `bar_shared`.
`foo_shared` uses a linker script \*.lds file to control which
symbols should be exported. The `cc_shared_library` rule logic does
not control which symbols get exported, it only uses what is assumed to be
exported to give errors during analysis phase if two shared libraries export the
same targets.
Every direct dependency of `cc_shared_library` is assumed to be
exported. Therefore, Bazel assumes during analysis that `foo` is being
exported by `foo_shared`. `baz` is not assumed to be exported
by `foo_shared`. Every target matched by the `exports_filter`
is also assumed to be exported.
Every single `cc_library` in the example should appear at most in one
`cc_shared_library`. If we wanted to link `baz` also into
`bar_shared` we would need to add
`tags = ["LINKABLE_MORE_THAN_ONCE"]` to `baz`.
Due to the `shared_lib_name` attribute, the file produced by
`bar_shared` will have the name `bar.so` as opposed
to the name `libbar.so` that it would have by default on Linux.
#### Errors
##### `Two shared libraries in dependencies export the same symbols.`
This will happen whenever you are creating a target with two different
`cc_shared_library` dependencies that export the same target. To fix this
you need to stop the libraries from being exported in one of the
`cc_shared_library` dependencies.
##### `Two shared libraries in dependencies link the same library statically`
This will happen whenever you are creating a new `cc_shared_library` with two
different `cc_shared_library` dependencies that link the same target statically.
Similar to the error with exports.
One way to fix this is to stop linking the library into one of the
`cc_shared_library` dependencies. At the same time, the one that still links it
needs to export the library so that the one not linking it keeps visibility to
the symbols. Another way is to pull out a third library that exports the target.
A third way is to tag the culprit `cc_library` with `LINKABLE_MORE_THAN_ONCE`
but this fix should be rare and you should absolutely make sure that the
`cc_library` is indeed safe to link more than once.
##### `` '//foo:foo' is already linked statically in '//bar:bar' but not exported` ``
This means that a library in the transitive closure of your `deps` is reachable
without going through one of the `cc_shared_library` dependencies but is already
linked into a different `cc_shared_library` in `dynamic_deps` and is not
exported.
The solution is to export it from the `cc_shared_library` dependency or pull out
a third `cc_shared_library` that exports it.
##### `Do not place libraries which only contain a precompiled dynamic library in deps.`
If you have a precompiled dynamic library, this doesn't need to and cannot be
linked statically into the current `cc_shared_library` target that you are
currently creating. Therefore, it doesn't belong in `deps` of the
`cc_shared_library`. If this precompiled dynamic library is a dependency of one
of your `cc_libraries`, then the `cc_library` needs to depend on it
directly.
##### `Trying to export a library already exported by a different shared library`
You will see this error if on the current rule you are claiming to export a
target that is already being exported by one of your dynamic dependencies.
To fix this, remove the target from `deps` and just rely on it from the dynamic
dependency or make sure that the `exports_filter` doesn't catch this target.
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `deps` | List of [labels](/concepts/labels); default is `[]` Top level libraries that will unconditionally be statically linked into the shared library after being whole-archived. Any transitive library dependency of these direct deps will be linked into this shared library as long as they have not already been linked by a `cc_shared_library` in `dynamic_deps`. During analysis, the rule implementation will consider any target listed in `deps` as being exported by the shared library in order to give errors when multiple `cc_shared_libraries` export the same targets. The rule implementation does not take care of informing the linker about which symbols should be exported by the shared object. The user should take care of this via linker scripts or visibility declarations in the source code. The implementation will also trigger errors whenever the same library is linked statically into more than one `cc_shared_library`. This can be avoided by adding `"LINKABLE_MORE_THAN_ONCE"` to the `cc_library.tags` or by listing the `cc_library` as an export of one of the shared libraries so that one can be made a `dynamic_dep` of the other. |
| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Any additional files that you may want to pass to the linker, for example, linker scripts. You have to separately pass any linker flags that the linker needs in order to be aware of this file. You can do so via the `user_link_flags` attribute. |
| `dynamic_deps` | List of [labels](/concepts/labels); default is `[]` These are other `cc_shared_library` dependencies the current target depends on. The `cc_shared_library` implementation will use the list of `dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the current target's `dynamic_deps`) to decide which `cc_libraries` in the transitive `deps` should not be linked in because they are already provided by a different `cc_shared_library`. |
| `exports_filter` | List of strings; default is `[]` This attribute contains a list of targets that are claimed to be exported by the current shared library. Any target `deps` is already understood to be exported by the shared library. This attribute should be used to list any targets that are exported by the shared library but are transitive dependencies of `deps`. Note that this attribute is not actually adding a dependency edge to those targets, the dependency edge should instead be created by `deps`.The entries in this attribute are just strings. Keep in mind that when placing a target in this attribute, this is considered a claim that the shared library exports the symbols from that target. The `cc_shared_library` logic doesn't actually handle telling the linker which symbols should be exported. The following syntax is allowed: `//foo:__pkg__` to account for any target in foo/BUILD `//foo:__subpackages__` to account for any target in foo/BUILD or any other package below foo/ like foo/bar/BUILD |
| `roots` | List of [labels](/concepts/labels); default is `[]` |
| `shared_lib_name` | String; default is `""` By default cc\_shared\_library will use a name for the shared library output file based on the target's name and the platform. This includes an extension and sometimes a prefix. Sometimes you may not want the default name, for example, when loading C++ shared libraries for Python the default lib\* prefix is often not desired, in which case you can use this attribute to choose a custom name. |
| `static_deps` | List of strings; default is `[]` |
| `user_link_flags` |
List of strings; default is `[]`
Any additional flags that you may want to pass to the linker. For example, to make the linker aware of a linker script passed via additional\_linker\_inputs you can use the following: `cc_shared_library( name = "foo_shared", additional_linker_inputs = select({ "//src/conditions:linux": [ ":foo.lds", ":additional_script.txt", ], "//conditions:default": []}), user_link_flags = select({ "//src/conditions:linux": [ "-Wl,-rpath,kittens", "-Wl,--version-script=$(location :foo.lds)", "-Wl,--script=$(location :additional_script.txt)", ], "//conditions:default": []}), ... )` |
| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. |
## cc\_static\_library
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/cc_static_library.bzl)
```
cc_static_library(name, deps, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, package_metadata, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility)
```
Produces a static library from a list of targets and their transitive dependencies.
The resulting static library contains the object files of the targets listed in
`deps` as well as their transitive dependencies, with preference given to
`PIC` objects.
#### Output groups
##### `linkdeps`
A text file containing the labels of those transitive dependencies of targets listed in
`deps` that did not contribute any object files to the static library, but do
provide at least one static, dynamic or interface library. The resulting static library
may require these libraries to be available at link time.
##### `linkopts`
A text file containing the user-provided `linkopts` of all transitive
dependencies of targets listed in `deps`.
#### Duplicate symbols
By default, the `cc_static_library` rule checks that the resulting static
library does not contain any duplicate symbols. If it does, the build fails with an error
message that lists the duplicate symbols and the object files containing them.
This check can be disabled per target or per package by setting
`features = ["-symbol_check"]` or globally via
`--features=-symbol_check`.
##### Toolchain support for `symbol_check`
The auto-configured C++ toolchains shipped with Bazel support the
`symbol_check` feature on all platforms, except on Windows when the toolchain
has been switched to clang-cl via `USE_CLANG_CL=1`: the check relies on a
`lib.exe` flag that `llvm-lib.exe` does not implement, so no duplicate
symbol check is performed there. Custom toolchains can add support for it in one of two
ways:
* Implementing the `ACTION_NAMES.validate_static_library` action and
enabling it with the `symbol_check` feature. The tool set in the action is
invoked with two arguments, the static library to check for duplicate symbols and the
path of a file that must be created if the check passes.
* Having the `symbol_check` feature add archiver flags that cause the
action creating the static library to fail on duplicate symbols.
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `deps` | List of [labels](/concepts/labels); default is `[]` The list of targets to combine into a static library, including all their transitive dependencies. Dependencies that do not provide any object files are not included in the static library, but their labels are collected in the file provided by the `linkdeps` output group. |
## cc\_test
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/cc_test.bzl)
```
cc_test(name, deps, srcs, data, additional_compiler_inputs, additional_linker_inputs, args, aspect_hints, compatible_with, conlyopts, copts, cxxopts, defines, deprecation, dynamic_deps, env, env_inherit, exec_compatible_with, exec_group_compatible_with, exec_properties, features, flaky, hdrs_check, includes, licenses, link_extra_lib, linkopts, linkshared, linkstatic, local, local_defines, local_includes, malloc, module_interfaces, nocopts, package_metadata, reexport_deps, restricted_to, shard_count, size, stamp, tags, target_compatible_with, testonly, timeout, toolchains, visibility, win_def_file)
```
A `cc_test()` rule compiles a test. Here, a test
is a binary wrapper around some testing code.
*By default, C++ tests are dynamically linked.*
To statically link a unit test, specify
[`linkstatic=True`](/reference/be/c-cpp#cc_binary.linkstatic).
It would probably be good to comment why your test needs
`linkstatic`; this is probably not obvious.
#### Implicit output targets
* `name.stripped` (only built if explicitly requested): A stripped
version of the binary. `strip -g` is run on the binary to remove debug
symbols. Additional strip options can be provided on the command line using
`--stripopt=-foo`.
* `name.dwp` (only built if explicitly requested): If
[Fission](https://gcc.gnu.org/wiki/DebugFission) is enabled: a debug
information package file suitable for debugging remotely deployed binaries. Else: an
empty file.
See the [cc\_binary()](/reference/be/c-cpp#cc_binary_args) arguments, except that
the `stamp` argument is set to 0 by default for tests and
that `cc_test` has extra [attributes common to all test rules (\*\_test)](/reference/be/common-definitions#common-attributes-tests).
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `deps` | List of [labels](/concepts/labels); default is `[]` The list of other libraries to be linked in to the binary target. These can be `cc_library` or `objc_library` targets. It is also allowed to put linker scripts (.lds) into deps, and reference them in [`linkopts`](#cc_binary.linkopts), but please consider [`additional_linker_inputs`](#cc_binary.additional_linker_inputs) for that use case. |
| `srcs` |
The list of C and C++ files that are processed to create the library target. These are C/C++ source and header files, either non-generated (normal source code) or generated.
All `.cc`, `.c`, and `.cpp` files will be compiled. These might be generated files: if a named file is in the `outs` of some other rule, this `cc_library` will automatically depend on that other rule.
Pure assembler files (.s, .asm) are not preprocessed and are typically built using the assembler. Preprocessed assembly files (.S) are preprocessed and are typically built using the C/C++ compiler.
A `.h` file will not be compiled, but will be available for inclusion by sources in this rule. Both `.cc` and `.h` files can directly include headers listed in these `srcs` or in the `hdrs` of this rule or any rule listed in the `deps` argument.
All `#include`d files must be mentioned in the `hdrs` attribute of this or referenced `cc_library` rules, or they should be listed in `srcs` if they are private to this library. See "Header inclusion checking" for a more detailed description.
`.so`, `.lo`, and `.a` files are pre-compiled files. Your library might have these as `srcs` if it uses third-party code for which we don't have source code.
If the `srcs` attribute includes the label of another rule, `cc_library` will use the output files of that rule as source files to compile. This is useful for one-off generation of source code (for more than occasional use, it's better to implement a Starlark rule class and use the `cc_common` API)
Permitted `srcs` file types:
C and C++ source files: `.c`, `.cc`, `.cpp`, `.cxx`, `.c++`, `.C`
C and C++ header files: `.h`, `.hh`, `.hpp`, `.hxx`, `.inc`, `.inl`, `.H`
Assembler with C preprocessor: `.S`
Archive: `.a`, `.pic.a`
"Always link" library: `.lo`, `.pic.lo`
Shared library, versioned or unversioned: `.so`, `.so.version`
Object file: `.o`, `.pic.o`
... and any rules that produce those files (e.g. `cc_embed_data`). Different extensions denote different programming languages in accordance with gcc convention.
If a `data` is the name of a generated file, then this `cc_library` rule automatically depends on the generating rule.
If a `data` is a rule name, then this `cc_library` rule automatically depends on that rule, and that rule's `outs` are automatically added to this `cc_library`'s data files.
Your C++ code can access these data files like so:
`const std::string path = devtools_build::GetDataDependencyFilepath( "my/test/data/file");` |
| `additional_compiler_inputs` | List of [labels](/concepts/labels); default is `[]` Any additional files you might want to pass to the compiler command line, such as sanitizer ignorelists, for example. Files specified here can then be used in copts with the \$(location) function. |
| `additional_linker_inputs` | List of [labels](/concepts/labels); default is `[]` Dependencies that are only made available to the C++ linker command. Unlike `deps`, which is conceptually made for both compilation and linking dependencies, `additional_linker_inputs` is specifically made for only the latter, and signals a dependency that is required only for linking (for example, files that are referenced in `linkopts`). For example, compiled Windows .res files can be provided here to be embedded in the binary target. |
| `conlyopts` | List of strings; default is `[]` Add these options to the C compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). |
| `copts` | List of strings; default is `[]` Add these options to the C/C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string in this attribute is added in the given order to `COPTS` before compiling the binary target. The flags take effect only for compiling this target, not its dependencies, so be careful about header files included elsewhere. All paths should be relative to the workspace, not to the current package. This attribute should not be needed outside of `third_party`. If the package declares the [feature](/reference/be/functions#package.features) `no_copts_tokenization`, Bourne shell tokenization applies only to strings that consist of a single "Make" variable. |
| `cxxopts` | List of strings; default is `[]` Add these options to the C++ compilation command. Subject to ["Make variable"](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). |
| `defines` | List of strings; default is `[]` List of defines to add to the compile line of this and all dependent targets. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line to this target, as well as to every rule that depends on it. Be very careful, since this may have far-reaching effects -- the defines are added to every target that depends on this target. When in doubt, add define values to [`local_defines`](#cc_binary.local_defines) instead. |
| `dynamic_deps` | List of [labels](/concepts/labels); default is `[]` These are other `cc_shared_library` dependencies the current target depends on. The `cc_shared_library` implementation will use the list of `dynamic_deps` (transitively, i.e. also the `dynamic_deps` of the current target's `dynamic_deps`) to decide which `cc_libraries` in the transitive `deps` should not be linked in because they are already provided by a different `cc_shared_library`. |
| `hdrs_check` | String; default is `""` Deprecated, no-op. |
| `includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-I path_to_package/include_entry`. This should only be used for third-party libraries that do not conform to the Google style of writing #include statements. Unlike [COPTS](#cc_binary.copts), these flags are added for this rule and every rule that depends on it. (Note: not the rules it depends upon!) Be very careful, since this may have far-reaching effects. When the include path is only needed to compile this target, use [`local_includes`](#cc_binary.local_includes) instead. The added `include` paths will include generated files as well as files in the source tree. |
| `link_extra_lib` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:link_extra_lib"` Control linking of extra libraries. By default, C++ binaries are linked against `@bazel_tools//tools/cpp:link_extra_lib`, which by default depends on the label flag `@bazel_tools//tools/cpp:link_extra_libs`. Without setting the flag, this library is empty by default. Setting the label flag allows linking optional dependencies, such as overrides for weak symbols, interceptors for shared library functions, or special runtime libraries (for malloc replacements, prefer `malloc` or `--custom_malloc`). Setting this attribute to `None` disables this behaviour. |
| `linkopts` | List of strings; default is `[]` Add these flags to the C++ linker command. Subject to ["Make" variable](make-variables) substitution, [Bourne shell tokenization](common-definitions#sh-tokenization) and [label expansion](common-definitions#label-expansion). Each string in this attribute is added to `LINKOPTS` before linking the binary target. Each element of this list that does not start with `$` or `-` is assumed to be the label of a target in `deps`. The list of files generated by that target is appended to the linker options. An error is reported if the label is invalid, or is not declared in `deps`. |
| `linkshared` | Boolean; default is `False` Create a shared library. To enable this attribute, include `linkshared=True` in your rule. By default this option is off. The presence of this flag means that linking occurs with the `-shared` flag to `gcc`, and the resulting shared library is suitable for loading into for example a Java program. However, for build purposes it will never be linked into the dependent binary, as it is assumed that shared libraries built with a [cc\_binary](#cc_binary) rule are only loaded manually by other programs, so it should not be considered a substitute for the [cc\_library](#cc_library) rule. For sake of scalability we recommend avoiding this approach altogether and simply letting `java_library` depend on `cc_library` rules instead. If you specify both `linkopts=['-static']` and `linkshared=True`, you get a single completely self-contained unit. If you specify both `linkstatic=True` and `linkshared=True`, you get a single, mostly self-contained unit. |
| `linkstatic` |
Boolean; default is `False`
For `cc_binary` and `cc_test`: link the binary in static mode. For `cc_library.link_static`: see below.
By default this option is on for `cc_binary` and off for the rest.
If enabled and this is a binary or test, this option tells the build tool to link in `.a`'s instead of `.so`'s for user libraries whenever possible. System libraries such as libc (but not the C/C++ runtime libraries, see below) are still linked dynamically, as are libraries for which there is no static library. So the resulting executable will still be dynamically linked, hence only mostly static.
There are really three different ways to link an executable:
STATIC with fully\_static\_link feature, in which everything is linked statically; e.g. "`gcc -static foo.o libbar.a libbaz.a -lm`". This mode is enabled by specifying `fully_static_link` in the `features` attribute.
STATIC, in which all user libraries are linked statically (if a static version is available), but where system libraries (excluding C/C++ runtime libraries) are linked dynamically, e.g. "`gcc foo.o libfoo.a libbaz.a -lm`". This mode is enabled by specifying `linkstatic=True`.
DYNAMIC, in which all libraries are linked dynamically (if a dynamic version is available), e.g. "`gcc foo.o libfoo.so libbaz.so -lm`". This mode is enabled by specifying `linkstatic=False`.
If the `linkstatic` attribute or `fully_static_link` in `features` is used outside of `//third_party` please include a comment near the rule to explain why.
The `linkstatic` attribute has a different meaning if used on a `cc_library()` rule. For a C++ library, `linkstatic=True` indicates that only static linking is allowed, so no `.so` will be produced. linkstatic=False does not prevent static libraries from being created. The attribute is meant to control the creation of dynamic libraries.
There should be very little code built with `linkstatic=False` in production. If `linkstatic=False`, then the build tool will create symlinks to depended-upon shared libraries in the `*.runfiles` area.
|
| `local_defines` | List of strings; default is `[]` List of defines to add to the compile line. Subject to ["Make" variable](/reference/be/make-variables) substitution and [Bourne shell tokenization](/reference/be/common-definitions#sh-tokenization). Each string, which must consist of a single Bourne shell token, is prepended with `-D` and added to the compile command line for this target, but not to its dependents. Unlike `defines`, the defines are only added to the compile command line for this target. |
| `local_includes` | List of strings; default is `[]` List of include dirs to be added to the compile line. Subject to ["Make variable"](/reference/be/make-variables) substitution. Each string is prepended with the package path and passed to the C++ toolchain for expansion via the "include\_paths" CROSSTOOL feature. A toolchain running on a POSIX system with typical feature definitions will produce `-I path_to_package/local_include_entry`. Unlike [INCLUDES](#cc_binary.includes), these flags are added for this target and not added to every target that depends on it. The `local_includes` paths will include generated files as well as files in the source tree. |
| `malloc` | [Label](/concepts/labels); default is `"@bazel_tools//tools/cpp:malloc"` Override the default dependency on malloc. By default, C++ binaries are linked against `//tools/cpp:malloc`, which is an empty library so the binary ends up using libc malloc. This label must refer to a `cc_library`. If compilation is for a non-C++ rule, this option has no effect. The value of this attribute is ignored if `linkshared=True` is specified. |
| `module_interfaces` |
The list of files are regarded as C++20 Modules Interface.
C++ Standard has no restriction about module interface file extension
Clang use cppm
GCC can use any source file extension
MSVC use ixx
The use is guarded by the flag `--experimental_cpp_modules`.
|
| `nocopts` | String; default is `""` Deprecated, no-op. |
| `reexport_deps` | List of [labels](/concepts/labels); default is `[]` |
| `stamp` |
Integer; default is `0`
Whether to encode build information into the binary. Possible values:
`stamp = 1`: Always stamp the build information into the binary, even in `--nostamp` builds. This setting should be avoided, since it potentially kills remote caching for the binary and any downstream actions that depend on it.
`stamp = 0`: Always replace build information by constant values. This gives good build result caching.
`stamp = -1`: Embedding of build information is controlled by the `--[no]stamp` flag.
Stamped binaries are not rebuilt unless their dependencies change.
|
| `win_def_file` | [Label](/concepts/labels); default is `None` The Windows DEF file to be passed to linker. This attribute should only be used when Windows is the target platform. It can be used to [export symbols](https://msdn.microsoft.com/en-us/library/d91k01sh.aspx) during linking a shared library. |
## cc\_toolchain
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/cc_toolchain.bzl)
```
cc_toolchain(name, all_files, ar_files, args, artifact_name_patterns, as_files, aspect_hints, compatible_with, compiler, compiler_files, compiler_files_without_includes, coverage_files, cpu, deprecation, dwp_files, dynamic_runtime_lib, enabled_features, exec_compatible_with, exec_group_compatible_with, exec_properties, exec_transition_for_inputs, features, grep_includes, known_features, legacy_tools, libc_top, licenses, linker_files, make_variables, module_map, objcopy_files, output_licenses, package_metadata, restricted_to, static_runtime_lib, strip_files, supports_header_parsing, supports_param_files, tags, target_compatible_with, target_libc, target_system_name, testonly, tool_map, toolchain_config, toolchain_identifier, toolchains, visibility)
```
Represents a C++ toolchain.
This rule is responsible for:
* Collecting all artifacts needed for C++ actions to run. This is done by
attributes such as `all_files`, `compiler_files`,
`linker_files`, or other attributes ending with `_files`). These are
most commonly filegroups globbing all required files.
* Generating correct command lines for C++ actions. This is done using
`CcToolchainConfigInfo` provider (details below).
Use `toolchain_config` attribute to configure the C++ toolchain.
See also this
[page](https://bazel.build/docs/cc-toolchain-config-reference) for elaborate C++ toolchain configuration and toolchain selection documentation.
Use `tags = ["manual"]` in order to prevent toolchains from being built and configured
unnecessarily when invoking `bazel build //...`
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `all_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts. These artifacts will be added as inputs to all rules\_cc related actions (with the exception of actions that are using more precise sets of artifacts from attributes below). Bazel assumes that `all_files` is a superset of all other artifact-providing attributes (e.g. linkstamp compilation needs both compile and link files, so it takes `all_files`). This is what `cc_toolchain.files` contains, and this is used by all Starlark rules using C++ toolchain. |
| `ar_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for archiving actions. |
| `args` | List of [labels](/concepts/labels); default is `[]` |
| `artifact_name_patterns` | List of [labels](/concepts/labels); default is `[]` |
| `as_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for assembly actions. |
| `compiler` | String; default is `""` |
| `compiler_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for compile actions. |
| `compiler_files_without_includes` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for compile actions in case when input discovery is supported (currently Google-only). |
| `coverage_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for coverage actions. If not specified, all\_files are used. |
| `cpu` | String; default is `""` |
| `dwp_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for dwp actions. |
| `dynamic_runtime_lib` | [Label](/concepts/labels); default is `None` Dynamic library artifact for the C++ runtime library (e.g. libstdc++.so). This will be used when 'static\_link\_cpp\_runtimes' feature is enabled, and we're linking dependencies dynamically. |
| `enabled_features` | List of [labels](/concepts/labels); default is `[]` |
| `exec_transition_for_inputs` | Boolean; default is `False` Deprecated. No-op. |
| `grep_includes` | [Label](/concepts/labels); default is `None` |
| `known_features` | List of [labels](/concepts/labels); default is `[]` |
| `legacy_tools` | List of [labels](/concepts/labels); default is `[]` |
| `libc_top` | [Label](/concepts/labels); default is `None` A collection of artifacts for libc passed as inputs to compile/linking actions. |
| `linker_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for linking actions. |
| `make_variables` | List of [labels](/concepts/labels); default is `[]` |
| `module_map` | [Label](/concepts/labels); default is `None` Module map artifact to be used for modular builds. |
| `objcopy_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for objcopy actions. |
| `output_licenses` | List of strings; default is `[]` |
| `static_runtime_lib` | [Label](/concepts/labels); default is `None` Static library artifact for the C++ runtime library (e.g. libstdc++.a). This will be used when 'static\_link\_cpp\_runtimes' feature is enabled, and we're linking dependencies statically. |
| `strip_files` | [Label](/concepts/labels); default is `None` Collection of all cc\_toolchain artifacts required for strip actions. |
| `supports_header_parsing` | Boolean; default is `False` Set to True when cc\_toolchain supports header parsing actions. |
| `supports_param_files` | Boolean; default is `True` Set to True when cc\_toolchain supports using param files for linking actions. |
| `target_libc` | String; default is `""` |
| `target_system_name` | String; default is `""` |
| `tool_map` | [Label](/concepts/labels); default is `None` |
| `toolchain_config` | [Label](/concepts/labels); default is `None` The label of the rule providing `cc_toolchain_config_info`. |
| `toolchain_identifier` | String; default is `""` The identifier used to match this cc\_toolchain with the corresponding crosstool\_config.toolchain. Until issue [#5380](https://github.com/bazelbuild/bazel/issues/5380) is fixed this is the recommended way of associating `cc_toolchain` with `CROSSTOOL.toolchain`. It will be replaced by the `toolchain_config` attribute ([#5380](https://github.com/bazelbuild/bazel/issues/5380)). |
## fdo\_prefetch\_hints
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/fdo/fdo_prefetch_hints.bzl)
```
fdo_prefetch_hints(name, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, package_metadata, profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility)
```
Represents an FDO prefetch hints profile that is either in the workspace.
Examples:
```
fdo_prefetch_hints(
name = "hints",
profile = "//path/to/hints:profile.afdo",
)
```
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `profile` | [Label](/concepts/labels); required Label of the hints profile. The hints file has the .afdo extension The label can also point to an fdo\_absolute\_path\_profile rule. |
## fdo\_profile
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/fdo/fdo_profile.bzl)
```
fdo_profile(name, aspect_hints, changelist, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, memprof_profile, package_metadata, profile, proto_profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility)
```
Represents an FDO profile that is in the workspace.
Example:
```
fdo_profile(
name = "fdo",
profile = "//path/to/fdo:profile.zip",
)
```
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `changelist` | String; default is `"0"` The profile generation CL version. |
| `memprof_profile` | [Label](/concepts/labels); default is `None` Label of the MemProf profile. The profile is expected to have either a .profdata extension (for an indexed/symbolized memprof profile), or a .zip extension for a zipfile containing a memprof.profdata file. |
| `profile` | [Label](/concepts/labels); required Label of the FDO profile or a rule which generates it. The FDO file can have one of the following extensions: .profraw for unindexed LLVM profile, .profdata for indexed LLVM profile, .zip that holds an LLVM profraw profile, .afdo for AutoFDO profile, .xfdo for XBinary profile. The label can also point to an fdo\_absolute\_path\_profile rule. |
| `proto_profile` | [Label](/concepts/labels); default is `None` Label of the protobuf profile. |
## memprof\_profile
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/fdo/memprof_profile.bzl)
```
memprof_profile(name, aspect_hints, changelist, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, package_metadata, profile, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility)
```
Represents a MEMPROF profile that is in the workspace.
Example:
```
memprof_profile(
name = "memprof",
profile = "//path/to/memprof:profile.afdo",
)
```
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `changelist` | String; default is `"0"` The profile generation CL version. |
| `profile` | [Label](/concepts/labels); required Label of the MEMPROF profile. The profile is expected to have either a .profdata extension (for an indexed/symbolized memprof profile), or a .zip extension for a zipfile containing a memprof.profdata file. The label can also point to an fdo\_absolute\_path\_profile rule. |
## propeller\_optimize
[View rule source](https://github.com/bazelbuild/rules_cc/blob/master/cc/private/rules_impl/fdo/propeller_optimize.bzl)
```
propeller_optimize(name, aspect_hints, cc_profile, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, features, ld_profile, package_metadata, restricted_to, tags, target_compatible_with, testonly, toolchains, visibility)
```
Represents a Propeller optimization profile in the workspace.
Example:
```
propeller_optimize(
name = "layout",
cc_profile = "//path:cc_profile.txt",
ld_profile = "//path:ld_profile.txt"
)
```
### Arguments
| Attributes | |
| - | - |
| `name` | [Name](/concepts/labels#target-names); required A unique name for this target. |
| `cc_profile` | [Label](/concepts/labels); required Label of the profile passed to the various compile actions. This file has the .txt extension. |
| `ld_profile` | [Label](/concepts/labels); required Label of the profile passed to the link action. This file has the .txt extension. |
# Common definitions
Source: https://bazel.build/reference/be/common-definitions
This section defines various terms and concepts that are common to
many functions or build rules.
## Contents
* [Bourne shell tokenization](#sh-tokenization)
* [Label Expansion](#label-expansion)
* [Typical attributes defined by most build rules](#typical-attributes)
* [Attributes common to all build rules](#common-attributes)
* [Attributes common to all test rules (\*\_test)](#common-attributes-tests)
* [Attributes common to all binary rules (\*\_binary)](#common-attributes-binaries)
* [Configurable attributes](#configurable-attributes)
* [Implicit output targets](#implicit-outputs)
## Bourne shell tokenization
Certain string attributes of some rules are split into multiple
words according to the tokenization rules of the Bourne shell:
unquoted spaces delimit separate words, and single- and
double-quotes characters and backslashes are used to prevent
tokenization.
Those attributes that are subject to this tokenization are
explicitly indicated as such in their definitions in this document.
Attributes subject to "Make" variable expansion and Bourne shell
tokenization are typically used for passing arbitrary options to
compilers and other tools. Examples of such attributes are
`cc_library.copts` and `java_library.javacopts`.
Together these substitutions allow a
single string variable to expand into a configuration-specific list
of option words.
## Label expansion
Some string attributes of a very few rules are subject to label
expansion: if those strings contain a valid label as a
substring, such as `//mypkg:target`, and that label is a
declared prerequisite of the current rule, it is expanded into the
pathname of the file represented by the
[target](https://bazel.build/reference/glossary#target)
`//mypkg:target`.
Example attributes include `genrule.cmd` and
`cc_binary.linkopts`. The details may vary significantly in
each case, over such issues as: whether relative labels are
expanded; how labels that expand to multiple files are
treated, etc. Consult the rule attribute documentation for
specifics.
## Typical attributes defined by most build rules
This section describes attributes that are defined by many build rules,
but not all.
| Attribute | Description |
| - | - |
| `data` | List of [labels](/concepts/labels); default is `[]` Files needed by this rule at runtime. May list file or rule targets. Generally allows any target. The `runfiles` of targets in the `data` attribute appear in the `*.runfiles` area of any executable which is output by or has a runtime dependency on this target. This may include data files or binaries used when this target's [`srcs`](#typical.srcs) are executed. Typically, this includes the targets' default outputs and their transitive runfiles, but this depends on the implementation of the rules for those targets; most rules include their default outputs in their `runfiles`. See the [data dependencies](/concepts/dependencies#data-dependencies) section for more information about how to depend on and use data files. New rules should define a `data` attribute if they process inputs which might use other inputs at runtime. Rules' implementation functions must also [populate the target's runfiles](https://bazel.build/rules/rules#runfiles) from the outputs and runfiles of any `data` attribute, as well as runfiles from any dependency attribute which provides either source code or runtime dependencies. |
| `deps` | List of [labels](/concepts/labels); default is `[]` Dependencies for this target. Generally should only list rule targets. (Though some rules permit files to be listed directly in `deps`, this should be avoided when possible.) Language-specific rules generally limit the listed targets to those with specific [providers](https://bazel.build/extending/rules#providers). The precise semantics of what it means for a target to depend on another using `deps` are specific to the kind of rule, and the rule-specific documentation goes into more detail. For rules which process source code, `deps` generally specifies code dependencies used by the code in [`srcs`](#typical.srcs). Most often, a `deps` dependency is used to allow one module to use symbols defined in another module written in the same programming language and separately compiled. Cross-language dependencies are also permitted in many cases: For example, a `java_library` target may depend on C++ code in a `cc_library` target, by listing the latter in the `deps` attribute. See the definition of [dependencies](/concepts/build-ref#deps) for more information. |
| `licenses` | List of strings; [nonconfigurable](#configurable-attributes); default is `["none"]` A list of license-type strings to be used for this particular target. This is part of a deprecated licensing API that Bazel no longer uses. Don't use this. |
| `srcs` | List of [labels](/concepts/labels); default is `[]` Files processed or included by this rule. Generally lists files directly, but may list rule targets (like `filegroup` or `genrule`) to include their default outputs. Language-specific rules often require that the listed files have particular file extensions. |
## Attributes common to all build rules
This section describes attributes that are implicitly added to all build
rules.
| Attribute | Description |
| - | - |
| `aspect_hints` |
A list of arbitrary labels which is exposed to aspects (in particular - aspects invoked by this rule's reverse dependencies), but isn't exposed to this rule's own implementation. Consult documentation for language-specific rule sets for details about what effect a particular aspect hint would have.
You could think of an aspect hint as a richer alternative to a tag: while a tag conveys only a boolean state (the tag is either present or absent in the `tags` list), an aspect hint can convey arbitrary structured information in its providers.
In practice, aspect hints are used for interoperability between different language-specific rule sets. For example, imagine you have a `mylang_binary` target which needs to depend on an `otherlang_library` target. The MyLang-specific logic needs some additional information about the OtherLang target in order to use it, but `otherlang_library` doesn't provide this information because it knows nothing about MyLang. One solution might be for the MyLang rule set to define a `mylang_hint` rule which can be used to encode that additional information; the user can add the hint to their `otherlang_library`'s `aspect_hints`, and `mylang_binary` can use an aspect to collect the additional information from a MyLang-specific provider in the `mylang_hint`.
Targets listed in `aspect_hints` should be lightweight and minimal.
Language-specific logic should consider only aspect hints having providers relevant to that language, and should ignore any other aspect hints.
|
| `compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` The list of environments this target can be built for, in addition to default-supported environments. This is part of Bazel's constraint system, which lets users declare which targets can and cannot depend on each other. For example, externally deployable binaries shouldn't depend on libraries with company-secret code. See [ConstraintSemantics](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/analysis/constraints/ConstraintSemantics.java#L46) for details. |
| `deprecation` | String; [nonconfigurable](#configurable-attributes); default is `None` An explanatory warning message associated with this target. Typically this is used to notify users that a target has become obsolete, or has become superseded by another rule, is private to a package, or is perhaps considered harmful for some reason. It is a good idea to include some reference (like a webpage, a bug number or example migration CLs) so that one can easily find out what changes are required to avoid the message. If there is a new target that can be used as a drop in replacement, it is a good idea to just migrate all users of the old target. This attribute has no effect on the way things are built, but it may affect a build tool's diagnostic output. The build tool issues a warning when a rule with a `deprecation` attribute is depended upon by a target in another package. Intra-package dependencies are exempt from this warning, so that, for example, building the tests of a deprecated rule does not encounter a warning. If a deprecated target depends on another deprecated target, no warning message is issued. Once people have stopped using it, the target can be removed. |
| `exec_compatible_with` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` A list of `constraint_values` that must be present in the execution platform of this target's default exec group. This is in addition to any constraints already set by the rule type. Constraints are used to restrict the list of available execution platforms. For more details, see the description of [toolchain resolution](/docs/toolchains#toolchain-resolution). and [exec groups](/extending/exec-groups) |
| `exec_group_compatible_with` | Dictionary of strings to lists of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `{}` A dictionary of exec group names to lists of `constraint_values` that must be present in the execution platform for the given exec group. This is in addition to any constraints already set on the exec group's definition. Constraints are used to restrict the list of available execution platforms. For more details, see the description of [toolchain resolution](/docs/toolchains#toolchain-resolution). and [exec groups](/extending/exec-groups) |
| `exec_properties` | Dictionary of strings; default is `{}` A dictionary of strings that will be added to the `exec_properties` of a platform selected for this target. See `exec_properties` of the [platform](platforms-and-toolchains#platform) rule. If a key is present in both the platform and target-level properties, the value will be taken from the target. Keys can be prefixed with the name of an execution group followed by a `.` to apply them only to that particular exec group. |
| `features` | List of *feature* strings; default is `[]` A feature is string tag that can be enabled or disabled on a target. The meaning of a feature depends on the rule itself. This `features` attribute is combined with the [package](/reference/be/functions#package) level `features` attribute. For example, if the features \["a", "b"] are enabled on the package level, and a target's `features` attribute contains \["-a", "c"], the features enabled for the rule will be "b" and "c". [See example](https://github.com/bazelbuild/examples/blob/main/rules/features/BUILD). |
| `package_metadata` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is the package's `default_package_metadata` A list of labels that are associated metadata about this target. Typically, the labels are simple rules that return a provider of constant values. Rules and aspects may use these labels to perform some additional analysis on the build graph. The canonical use case is that of [rules\_license](https://github.com/bazelbuild/rules_license). For that use case, `package_metadata` and `default_package_metadata` is used to attach information about a package's licence or version to targets. An aspect applied to a top-level binary can be used to gather those and produce compliance reports. |
| `restricted_to` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default is `[]` The list of environments this target can be built for, *instead* of default-supported environments. This is part of Bazel's constraint system. See [`compatible_with`](#common.compatible_with) for details. |
| `tags` |
Tags can be used on any rule. Tags on test and `test_suite` rules are useful for categorizing the tests. Tags on non-test targets are used to control sandboxed execution of `genrule`s and Starlark actions, and for parsing by humans and/or external tools.
Bazel modifies the behavior of its sandboxing code if it finds the following keywords in the `tags` attribute of any test or `genrule` target, or the keys of `execution_requirements` for any Starlark action.
`no-sandbox` keyword results in the action or test never being sandboxed; it can still be cached or run remotely - use `no-cache` or `no-remote` to prevent either or both of those.
`no-cache` keyword results in the action or test never being cached (locally or remotely). Note: for the purposes of this tag, the disk cache is considered a local cache, whereas the HTTP and gRPC caches are considered remote. Other caches, such as Skyframe or the persistent action cache, are not affected.
`no-remote-cache` keyword results in the action or test never being cached remotely (but it may be cached locally; it may also be executed remotely). Note: for the purposes of this tag, the disk cache is considered a local cache, whereas the HTTP and gRPC caches are considered remote. Other caches, such as Skyframe or the persistent action cache, are not affected. If a combination of local disk cache and remote cache are used (combined cache), it's treated as a remote cache and disabled entirely unless `--incompatible_remote_results_ignore_disk` is set in which case the local components will be used.
`no-remote-exec` keyword results in the action or test never being executed remotely (but it may be cached remotely).
`no-remote` keyword prevents the action or test from being executed remotely or cached remotely. This is equivalent to using both `no-remote-cache` and `no-remote-exec`.
`no-remote-cache-upload` keyword disables upload part of remote caching of a spawn. it does not disable remote execution.
`local` keyword precludes the action or test from being remotely cached, remotely executed, or run inside the sandbox. For genrules and tests, marking the rule with the `local = True` attribute has the same effect.
`requires-network` keyword allows access to the external network from inside the sandbox. This tag only has an effect if sandboxing is enabled.
`block-network` keyword blocks access to the external network from inside the sandbox. In this case, only communication with localhost is allowed. This tag only has an effect if sandboxing is enabled.
`requires-fakeroot` runs the test or action as uid and gid 0 (i.e., the root user). This is only supported on Linux. This tag takes precedence over the `--sandbox_fake_username` command-line option.
Tags on tests are generally used to annotate a test's role in your debug and release process. Typically, tags are most useful for C++ and Python tests, which lack any runtime annotation ability. The use of tags and size elements gives flexibility in assembling suites of tests based around codebase check-in policy.
Bazel modifies test running behavior if it finds the following keywords in the `tags` attribute of the test rule:
`exclusive` will force the test to be run in the "exclusive" mode, ensuring that no other tests are running at the same time. Such tests will be executed in serial fashion after all build activity and non-exclusive tests have been completed. Remote execution is disabled for such tests because Bazel doesn't have control over what's running on a remote machine.
`exclusive-if-local` will force the test to be run in the "exclusive" mode if it is executed locally, but will run the test in parallel if it's executed remotely.
`manual` keyword will exclude the target from expansion of target pattern wildcards (`...`, `:*`, `:all`, etc.) and `test_suite` rules which do not list the test explicitly when computing the set of top-level targets to build/run for the `build`, `test`, and `coverage` commands. It does not affect target wildcard or test suite expansion in other contexts, including the `query` command. Note that `manual` does not imply that a target should not be built/run automatically by continuous build/test systems. For example, it may be desirable to exclude a target from `bazel test ...` because it requires specific Bazel flags, but still have it included in properly-configured presubmit or continuous test runs.
`external` keyword will force test to be unconditionally executed (regardless of `--cache_test_results` value).
See Tag Conventions in the Test Encyclopedia for more conventions on tags attached to test targets. |
| `target_compatible_with` | List of [labels](/concepts/labels); default is `[]` A list of `constraint_value`s that must be present in the target platform and `config_setting`s that must match the target configuration for this target to be considered *compatible*. This is in addition to any constraints already set by the rule type. If the target platform does not satisfy all listed constraints, or the target configuration does not match all listed config\_settings, then the target is considered *incompatible*. Incompatible targets are skipped for building and testing when the target pattern is expanded (e.g. `//...`, `:all`). When explicitly specified on the command line, incompatible targets cause Bazel to print an error and cause a build or test failure. Targets that transitively depend on incompatible targets are themselves considered incompatible. They are also skipped for building and testing. An empty list (which is the default) signifies that the target is compatible with all platforms. All rules support this attribute. For some rules this attribute has no effect. For example, specifying `target_compatible_with` for a `cc_toolchain` is not useful. See the [Platforms](/docs/platforms#skipping-incompatible-targets) page for more information about incompatible target skipping. |
| `testonly` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` except for test and test suite targets If `True`, only testonly targets (such as tests) can depend on this target. Equivalently, a rule that is not `testonly` is not allowed to depend on any rule that is `testonly`. Tests (`*_test` rules) and test suites ([test\_suite](/reference/be/general#test_suite) rules) are `testonly` by default. This attribute is intended to mean that the target should not be contained in binaries that are released to production. Because testonly is enforced at build time, not run time, and propagates virally through the dependency tree, it should be applied judiciously. For example, stubs and fakes that are useful for unit tests may also be useful for integration tests involving the same binaries that will be released to production, and therefore should probably not be marked testonly. Conversely, rules that are dangerous to even link in, perhaps because they unconditionally override normal behavior, should definitely be marked testonly. |
| `toolchains` |
The set of targets whose Make variables this target is allowed to access. These targets are either instances of rules that provide `TemplateVariableInfo` or special targets for toolchain types built into Bazel. These include:
`@bazel_tools//tools/cpp:toolchain_type`
`@rules_java//toolchains:current_java_runtime`
Note that this is distinct from the concept of toolchain resolution that is used by rule implementations for platform-dependent configuration. You cannot use this attribute to determine which specific `cc_toolchain` or `java_toolchain` a target will use.
|
| `visibility` | List of [labels](/concepts/labels); [nonconfigurable](#configurable-attributes); default varies The `visibility` attribute controls whether the target can be depended on by targets in other locations. See the documentation for [visibility](/concepts/visibility). For targets declared directly in a BUILD file or in legacy macros called from a BUILD file, the default value is the package's `default_visibility` if specified, or else `["//visibility:private"]`. For targets declared in one or more symbolic macros, the default value is always just `["//visibility:private"]` (which makes it useable only within the package containing the macro's code). |
## Attributes common to all test rules (\*\_test)
This section describes attributes that are common to all test rules.
| Attribute | Description |
| - | - |
| `args` | List of strings; subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution, and [Bourne shell tokenization](#sh-tokenization); default is `[]` Command line arguments that Bazel passes to the target when it is executed with `bazel test`. These arguments are passed before any `--test_arg` values specified on the `bazel test` command line. |
| `env` | Dictionary of strings; values are subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution; default is `{}` Specifies additional environment variables to set when the test is executed by `bazel test`. This attribute only applies to native rules, like `cc_test`, `py_test`, and `sh_test`. It does not apply to Starlark-defined test rules. For your own Starlark rules, you can add an "env" attribute and use it to populate a [RunEnvironmentInfo](/rules/lib/providers/RunEnvironmentInfo) Provider. [TestEnvironment](/rules/lib/toplevel/testing#TestEnvironment) Provider. |
| `env_inherit` | List of strings; default is `[]` Specifies additional environment variables to inherit from the external environment when the test is executed by `bazel test`. This attribute only applies to native rules, like `cc_test`, `py_test`, and `sh_test`. It does not apply to Starlark-defined test rules. |
| `size` |
String `"enormous"`, `"large"`, `"medium"`, or `"small"`; nonconfigurable; default is `"medium"`
Specifies a test target's "heaviness": how much time/resources it needs to run.
Unit tests are considered "small", integration tests "medium", and end-to-end tests "large" or "enormous". Bazel uses the size to determine a default timeout, which can be overridden using the `timeout` attribute. The timeout is for all tests in the BUILD target, not for each individual test. When the test is run locally, the `size` is additionally used for scheduling purposes: Bazel tries to respect `--local_{ram,cpu}_resources` and not overwhelm the local machine by running lots of heavy tests at the same time.
Test sizes correspond to the following default timeouts and assumed peak local resource usages:
Size
RAM (in MB)
CPU (in CPU cores)
Default timeout
small
20
1
short (1 minute)
medium
100
1
moderate (5 minutes)
large
300
1
long (15 minutes)
enormous
800
1
eternal (60 minutes)
The environment variable `TEST_SIZE` will be set to the value of this attribute when spawning the test.
|
| `timeout` |
String `"short"`, `"moderate"`, `"long"`, or `"eternal"`; nonconfigurable; default is derived from the test's `size` attribute
How long the test is expected to run before returning.
While a test's size attribute controls resource estimation, a test's timeout may be set independently. If not explicitly specified, the timeout is based on the test's size. The test timeout can be overridden with the `--test_timeout` flag, e.g. for running under certain conditions which are known to be slow. Test timeout values correspond to the following time periods:
Timeout Value
Time Period
short
1 minute
moderate
5 minutes
long
15 minutes
eternal
60 minutes
For times other than the above, the test timeout can be overridden with the `--test_timeout` bazel flag, e.g. for manually running under conditions which are known to be slow. The `--test_timeout` values are in seconds. For example `--test_timeout=120` will set the test timeout to two minutes.
The environment variable `TEST_TIMEOUT` will be set to the test timeout (in seconds) when spawning the test.
|
| `flaky` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` Marks test as flaky. If set, executes the test up to three times, marking it as failed only if it fails each time. By default, this attribute is set to False and the test is executed only once. Note, that use of this attribute is generally discouraged - tests should pass reliably when their assertions are upheld. |
| `shard_count` | Non-negative integer less than or equal to 50; default is `-1` Specifies the number of parallel shards to use to run the test. If set, this value will override any heuristics used to determine the number of parallel shards with which to run the test. Note that for some test rules, this parameter may be required to enable sharding in the first place. Also see `--test_sharding_strategy`. If test sharding is enabled, the environment variable `TEST_TOTAL_SHARDS` will be set to this value when spawning the test. Sharding requires the test runner to support the test sharding protocol. If it does not, then it will most likely run every test in every shard, which is not what you want. See [Test Sharding](/reference/test-encyclopedia#test-sharding) in the Test Encyclopedia for details on sharding. |
| `local` | Boolean; [nonconfigurable](#configurable-attributes); default is `False` Forces the test to be run locally, without sandboxing. Setting this to True is equivalent to providing "local" as a tag (`tags=["local"]`). |
## Attributes common to all binary rules (\*\_binary)
This section describes attributes that are common to all binary rules.
| Attribute | Description |
| - | - |
| `args` | List of strings; subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution, and [Bourne shell tokenization](#sh-tokenization); [nonconfigurable](#configurable-attributes); default is `[]` Command line arguments that Bazel will pass to the target when it is executed either by the `run` command or as a test. These arguments are passed before the ones that are specified on the `bazel run` or `bazel test` command line. *NOTE: The arguments are not passed when you run the target outside of Bazel (for example, by manually executing the binary in `bazel-bin/`).* |
| `env` | Dictionary of strings; values are subject to [\$(location)](/reference/be/make-variables#predefined_label_variables) and ["Make variable"](/reference/be/make-variables) substitution; default is `{}` Specifies additional environment variables to set when the target is executed by `bazel run`. This attribute only applies to native rules, like `cc_binary`, `py_binary`, and `sh_binary`. It does not apply to Starlark-defined executable rules. For your own Starlark rules, you can add an "env" attribute and use it to populate a [RunEnvironmentInfo](/rules/lib/providers/RunEnvironmentInfo) Provider. *NOTE: The environment variables are not set when you run the target outside of Bazel (for example, by manually executing the binary in `bazel-bin/`).* |
| `output_licenses` | List of strings; default is `[]` The licenses of the output files that this binary generates. This is part of a deprecated licensing API that Bazel no longer uses. Don't use this. |
## Configurable attributes
Most attributes are "configurable", meaning that their values may change when
the target is built in different ways. Specifically, configurable attributes
may vary based on the flags passed to the Bazel command line, or what
downstream dependency is requesting the target. This can be used, for
instance, to customize the target for multiple platforms or compilation modes.
The following example declares different sources for different target
architectures. Running `bazel build :multiplatform_lib --cpu x86`
will build the target using `x86_impl.cc`, while substituting
`--cpu arm` will instead cause it to use `arm_impl.cc`.
```
cc_library(
name = "multiplatform_lib",
srcs = select({
":x86_mode": ["x86_impl.cc"],
":arm_mode": ["arm_impl.cc"]
})
)
config_setting(
name = "x86_mode",
values = { "cpu": "x86" }
)
config_setting(
name = "arm_mode",
values = { "cpu": "arm" }
)
```
The [`select()`](/reference/be/functions#select) function
chooses among different alternative values for a configurable attribute based
on which [`config_setting`](/reference/be/general#config_setting)
or [`constraint_value`](/reference/be/platforms-and-toolchains#constraint_value)
criteria the target's configuration satisfies.
Bazel evaluates configurable attributes after processing macros and before
processing rules (technically, between the
[loading and analysis phases](https://bazel.build/rules/concepts#evaluation-model)).
Any processing before `select()` evaluation doesn't know which
branch the `select()` chooses. Macros, for example, can't change
their behavior based on the chosen branch, and `bazel query` can
only make conservative guesses about a target's configurable dependencies. See
[this FAQ](https://bazel.build/docs/configurable-attributes#faq)
for more on using `select()` with rules and macros.
Attributes marked `nonconfigurable` in their documentation cannot
use this feature. Usually an attribute is nonconfigurable because Bazel
internally needs to know its value before it can determine how to resolve a
`select()`.
See [Configurable Build Attributes](https://bazel.build/docs/configurable-attributes) for a detailed overview.
## Implicit output targets
*Implicit outputs in C++ are deprecated. Please refrain from using it
in other languages where possible. We don't have a deprecation path yet
but they will eventually be deprecated too.*
When you define a build rule in a BUILD file, you are explicitly
declaring a new, named rule target in a package. Many build rule
functions also *implicitly* entail one or more output file
targets, whose contents and meaning are rule-specific.
For example, when you explicitly declare a
`java_binary(name='foo', ...)` rule, you are also
*implicitly* declaring an output file
target `foo_deploy.jar` as a member of the same package.
(This particular target is a self-contained Java archive suitable
for deployment.)
Implicit output targets are first-class members of the global
target graph. Just like other targets, they are built on demand,
either when specified in the top-level built command, or when they
are necessary prerequisites for other build targets. They can be
referenced as dependencies in BUILD files, and can be observed in
the output of analysis tools such as `bazel query`.
For each kind of build rule, the rule's documentation contains a
special section detailing the names and contents of any implicit
outputs entailed by a declaration of that kind of rule.
An important but somewhat subtle distinction between the
two namespaces used by the build system:
[labels](/concepts/labels) identify *targets*,
which may be rules or files, and file targets may be divided into
either source (or input) file targets and derived (or output) file
targets. These are the things you can mention in BUILD files,
build from the command-line, or examine using `bazel query`;
this is the *target namespace*. Each file target corresponds
to one actual file on disk (the "file system namespace"); each rule
target may correspond to zero, one or more actual files on disk.
There may be files on disk that have no corresponding target; for
example, `.o` object files produced during C++ compilation
cannot be referenced from within BUILD files or from the command line.
In this way, the build tool may hide certain implementation details of
how it does its job. This is explained more fully in
the [BUILD Concept Reference](/concepts/build-ref).
# Extra Actions Rules
Source: https://bazel.build/reference/be/extra-actions
## Rules
* [action\_listener](#action_listener)
* [extra\_action](#extra_action)
## action\_listener
[View rule source](https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/rules/extra/ActionListenerRule.java)
```
action_listener(name, aspect_hints, compatible_with, deprecation, exec_compatible_with, exec_group_compatible_with, exec_properties, extra_actions, features, licenses, mnemonics, package_metadata, restricted_to, tags, target_compatible_with, testonly, visibility)
```
**WARNING:** Extra actions are deprecated. Use
[aspects](https://bazel.build/rules/aspects)
instead.
An `action_listener` rule doesn't produce any output itself.
Instead, it allows tool developers to insert
[`extra_action`](/reference/be/extra-actions#extra_action)s into the build system,
by providing a mapping from action to [`extra_action`](/reference/be/extra-actions#extra_action).
This rule's arguments map action mnemonics to
[`extra_action`](/reference/be/extra-actions#extra_action) rules.
By specifying the option [`--experimental_action_listener=