乐于分享
好东西不私藏

Bazel C++ 构建系列文档(十二):汇总概述

Bazel C++ 构建系列文档(十二):汇总概述

1. 常用 Bazel 命令参考

1.1 构建命令

# 基本构建bazel build //...                     # 构建所有目标bazel build //src:app                 # 构建特定目标bazel build //src/...                # 构建 src 包下所有目标# 构建选项bazel build //... -c opt              # 优化模式bazel build //... -c dbg              # 调试模式bazel build //... --config=release    # 使用自定义配置# 并发控制bazel build //... --jobs=8            # 8个并发任务bazel build //... --local_resources=8,12.0  # 8个CPU,12GB内存# 远程构建bazel build //... --remote_cache=grpc://cache:9092bazel build //... --remote_executor=grpc://executor:9091

1.2 测试命令

# 基本测试bazel test //...                      # 运行所有测试bazel test //tests:unit_tests         # 运行特定测试bazel test //... --test_output=all    # 显示所有测试输出# 测试过滤bazel test //... --test_filter="*Test"         # 只运行Testbazel test //... --test_tags_filters=unit      # 只运行unit测试bazel test //... --test_size_filters=small     # 只运行小测试# 测试配置bazel test //... --test_timeout=300           # 总超时300秒bazel test //... --runs_per_test=3            # 每个测试运行3次

1.3 查询命令

# 基本查询bazel query //...                     # 列出所有目标bazel query "kind(cc_library, //...)" # 查找所有库bazel query "deps(//:app)"           # 查询依赖# 高级查询bazel query "rdeps(//..., //:lib)"   # 查询反向依赖bazel query "somepath(//:a, //:b)"   # 查找路径bazel query --output=graph | dot -Tpng # 生成依赖图# cquery (配置查询)bazel cquery "kind(cc_binary, //...)" --output=label

1.4 分析命令

# 构建分析bazel build //... --build_profile=json:profile.jsonbazel analyze-profile profile.json --output_html=analysis.html# 依赖分析bazel query --output=tree "deps(//:app)"bazel mod graph                          # Bzlmod 依赖图

2. BUILD 文件参考

2.1 cc_library 属性

属性
类型
描述
默认值
name
string
目标名称
必需
srcs
list
源文件列表
hdrs
list
头文件列表
deps
list
依赖列表
copts
list
C编译选项
cxxopts
list
C++编译选项
linkopts
list
链接选项
defines
list
预处理器宏
includes
list
包含路径
visibility
list
可见性
[“//visibility:private”]
linkstatic
bool
是否静态链接
true
alwayslink
bool
是否始终链接
false
testonly
bool
是否只用于测试
false
feature
string
特性标签

2.2 cc_binary 属性

继承 cc_library 属性,额外属性:

属性
类型
描述
entry_point
string
入口符号(动态库)
features
list
链接特性

2.3 cc_test 属性

继承 cc_library 属性,额外属性:

属性
类型
描述
args
list
测试参数
data
list
测试数据文件
size
string
测试大小(small/medium/large)
timeout
int
超时时间(秒)
flaky
bool
是否不稳定

2.4 filegroup 属性

属性
类型
描述
srcs
list
文件列表
outs
list
输出文件
visibility
list
可见性
features
list
特性

3. WORKSPACE 参考指南

3.1 http_archive 属性

http_archive(    name = "example_lib",    urls = [        "https://github.com/example/lib/archive/v1.0.tar.gz",    ],    sha256 = "...",    strip_prefix = "lib-1.0",    build_file = "//third_party:lib.BUILD",    patch_cmds = ["sed -i 's/foo/bar/' file.txt"],)

3.2 git_repository 属性

git_repository(    name = "example_lib",    remote = "https://github.com/example/lib.git",    branch = "main",    # 或    tag = "v1.0.0",    commit = "a1b2c3d4...",)

3.3 local_repository 属性

local_repository(    name = "local_lib",    path = "../lib",  # 相对路径)

4. Bzlmod 参考

4.1 MODULE.bazel 语法

# 模块定义module(    name = "my_project",    version = "1.0.0",    compatibility_level = 1,)# 依赖声明bazel_dep(name = "abseil-cpp", version = "20230802.1")bazel_dep(name = "rules_cc", version = "0.0.9")# 扩展声明bazel_dep(name = "my_extension", repo_name = "example")

4.2 模块扩展

# extensions.bzldef _my_extension_impl(module_ctx):    # 实现逻辑    passmy_extension = module_extension(    implementation = _my_extension_impl,)# 使用my_extension = use_extension("//:extensions.bzl""my_extension")

5. 常用环境变量

5.1 构建环境变量

变量
描述
BAZELISK_VERSION
Bazelisk 版本
BAZEL_V2
启用 Bazel V2
COMPILATION_MODE
编译模式 (fastbuild/dbg/opt)
BAZEL_BUILD_FILE
自定义 BUILD 文件名

5.2 缓存环境变量

变量
描述
BAZEL_DISK_CACHE
磁盘缓存路径
BAZEL_REMOTE_CACHE
远程缓存地址
BAZEL_REMOTE_EXECUTOR
远程执行器地址

5.3 调试环境变量

变量
描述
VERBOSE
详细输出
BAZEL_BUILD_EXTRA_OPTIONS
额外构建选项
BAZEL_TEST_TIMEOUT
测试超时时间

6. 常用工具参考

6.1 buildifier

# 安装go install github.com/bazelbuild/buildtools/buildifier@latest# 使用buildifier --version                           # 查看版本buildifier *.bzl BUILD WORKSPACE                # 格式化文件buildifier --lint=warn --mode=check *.bzl      # 检查语法# 配置buildifier --diff                              # 显示差异buildifier --fix                               # 自动修复

6.2 bazel-diff

# 比较两次构建的差异bazel-diff \    --baseline=baseline \    --current=current \    --output-file=diff.txt

6.3 bazel-remote

# 启动远程缓存服务器bazel-remote \    --max_storage=100GiB \    --host=localhost:9092 \    --storage_path=/cache/bazel-remote

7. 故障排查指南

7.1 常见错误及解决方案

错误信息
可能原因
解决方案
no such target
目标不存在或拼写错误
检查 BUILD 文件和路径
circular dependency
循环依赖
检查依赖图,重新设计
build failed
编译错误
检查编译选项和依赖
test failed
测试失败
检查测试代码和数据
remote cache error
网络或认证问题
检查网络和证书

7.2 调试步骤

# 1. 启用详细日志bazel build //... --verbose# 2. 检查缓存bazel info --disk_cache_usage# 3. 查看详细错误bazel build //... --verbose_failures# 4. 分析构建bazel analyze-profile --build

7.3 性能问题排查

# 查看构建时间bazel build //... --experimental_show_spawn_timestamps# 分析 Action 时间bazel query --output=label "buildfiles(//...)" | \    xargs bazel build --action_env=VERBOSE=1# 监控资源使用top -p $(pgrep -f "bazel")

8. 最佳实践总结

8.1 项目结构

✅ 推荐的项目结构project/├── WORKSPACE / MODULE.bazel├── .bazelrc├── BUILD                    # 根包(可选)├── src/│   ├── BUILD│   ├── main.cc│   └── lib/├── lib/                     # 共享库│   ├── BUILD│   └── utils.h├── third_party/             # 第三方依赖│   ├── BUILD│   └── deps/├── tests/│   ├── BUILD│   └── unit/└── tools/                   # 构建工具    ├── buildifier/    └── scripts/

8.2 BUILD 文件最佳实践

# ✅ 好的实践cc_library(    name = "public_api",    srcs = ["api.cc"],    hdrs = ["api.h"],    deps = [        "//base:types",        # 精确依赖    ],    visibility = ["//visibility:public"],)# ❌ 坏的实践cc_library(    name = "everything",    srcs = glob(["**/*.cc"]),   # 过于宽泛    deps = ["//base:*"],        # 过度依赖)

8.3 依赖管理最佳实践

✅ 依赖管理原则─────────────────────────1. 始终显式声明依赖2. 使用版本锁定3. 依赖粒度适中4. 避免过度抽象5. 定期更新依赖6. 使用镜像源

9. 资源与链接

9.1 官方资源

  • Bazel 官方文档
  • Bazel GitHub
  • Bazel Central Registry
  • Bazel 邮件列表

9.2 社区资源

  • Bazel Slacks
  • Bazel 示例项目
  • Bazel 最佳实践
  • BazelCon 大会

9.3 学习资源

  • Bazel 教程
  • Bazel by Example
  • Bazel Internals
  • Bazel and Beyond

10. 版本兼容性

10.1 Bazel 版本支持

Bazel 版本
支持期限
主要特性
6.x
维护中
Bzlmod、rules_pkg
7.x
当前稳定
模块系统改进
8.x
开发中
更好的性能

10.2 C++ 标准支持

Bazel 版本
C++ 标准
要求的编译器
6.x
C++14
GCC 8+ / Clang 10+
7.x
C++17
GCC 9+ / Clang 12+
8.x
C++20
GCC 11+ / Clang 14+