bazel使用文档

简介

bazel是google开源的构建系统,支持多种语言、支持云端构建等功能。

bazel与cmake、autoconf不太一样,bazel进行构建时会启动一个服务,然后bazel命令与这个服务进行交互发送指令,这个服务实际进行编译任务。同时bazel提供了一套远程构建、缓存的接口,实现这套接口就可以制定自己的远程构建系统了。

环境搭建

bazel构建工具依赖java和python,bazel启动的构建服务是java开发的,bazel使用的构建配置是基于python写的,因此这两个组件并不可少。

bazel安装可以参考bazel提供的安装教程

bazel支持远程方案,包括远程构建构建缓存

buildform是其中一种解决方案,buildform基于java编写,分为调度服务和工作服务,支持多分片部署,详细文档可以见buildform的wiki。buildform的readme里有两个服务的简单启动命令,在examples目录下有对应的服务配置,使用对应的配置即可启动。

上面的环境部署好了之后,添加bazel的配置,bazel配置分为用户级别和项目级别,文件名为.bazel。添加下面内容,并在构建时添加 –config=build 即可实现远程编译:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Remote Build Execution requires a strong hash function, such as SHA256.
startup --host_jvm_args=-Dbazel.DigestFunction=SHA256

# Depending on how many machines are in the remote execution instance, setting
# this higher can make builds faster by allowing more jobs to run in parallel.
# Setting it too high can result in jobs that timeout, however, while waiting
# for a remote machine to execute them.
build:remote --jobs=8


# Set various strategies so that all actions execute remotely. Mixing remote
# and local execution will lead to errors unless the toolchain and remote
# machine exactly match the host machine.
build:remote --spawn_strategy=remote
build:remote --strategy=Javac=remote
build:remote --strategy=Closure=remote
build:remote --genrule_strategy=remote
build:remote --define=EXECUTOR=remote

# Enable the remote cache so action results can be shared across machines,
# developers, and workspaces.
build:remote --remote_cache=localhost:8080

# Enable remote execution so actions are performed on the remote systems.
build:remote --remote_executor=localhost:8080

# Enable encryption.
#build:remote --tls_enabled=true

# Enforce stricter environment rules, which eliminates some non-hermetic
# behavior and therefore improves both the remote cache hit rate and the
# correctness and repeatability of the build.
build:remote --experimental_strict_action_env=true

# Set a higher timeout value, just in case.
build:remote --remote_timeout=3600

build:remote --auth_enabled=false

# Since we're testing remote execution, let's make sure it always actually
# happens.
build:remote --remote_accept_cached=false
test --cache_test_results=false

test --test_output=errors

# TODO(b/77217487): Needed for C++ builds until fix to
# https://github.com/bazelbuild/bazel/issues/4883 is available.
build --nocheck_visibility

build:debug --verbose_failures
build:debug --explain=explain.txt
build:debug --verbose_explanations
build:debug --toolchain_resolution_debug
build:debug --subcommands

在mac上使用bazel构建linux产物的方法的讨论在: https://stackoverflow.com/questions/61567876/bazel-mixing-a-linux-remote-execution-platform-with-a-mac-os-local-platform 目前还没有实现。

bazel平台的概念可以参考文档Bazel自定义工具链

构建简单项目

使用复杂依赖管理