下载示例代码

  1. git clone https://github.com/bazelbuild/examples

C++ 代码在 examples/cpp-tutorial 下,目录结构如下:

  1. examples
  2. └── cpp-tutorial
  3. ├──stage1
  4. ├── main
  5. ├── BUILD
  6. └── hello-world.cc
  7. └── WORKSPACE
  8. ├──stage2
  9. ├── main
  10. ├── BUILD
  11. ├── hello-world.cc
  12. ├── hello-greet.cc
  13. └── hello-greet.h
  14. └── WORKSPACE
  15. └──stage3
  16. ├── main
  17. ├── BUILD
  18. ├── hello-world.cc
  19. ├── hello-greet.cc
  20. └── hello-greet.h
  21. ├── lib
  22. ├── BUILD
  23. ├── hello-time.cc
  24. └── hello-time.h
  25. └── WORKSPACE

使用 Bazel 构建

stage1

cpp-tutorial/stage1/mainBUILD 文件如下:

  1. cc_binary(
  2. name = "hello-world",
  3. srcs = ["hello-world.cc"],
  4. )

构建项目

  1. cd cpp-tutorial/stage1
  2. bazel build //main:hello-world

run

  1. bazel-bin/main/hello-world

查看依赖图

  1. bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" --output graph

可以在 http://viz-js.com/ 查看 graph
image.png

stage2

指定多个 target

cpp-tutorial/stage2/mainBUILD 文件如下:

  1. cc_library(
  2. name = "hello-greet",
  3. srcs = ["hello-greet.cc"],
  4. hdrs = ["hello-greet.h"],
  5. )
  6. cc_binary(
  7. name = "hello-world",
  8. srcs = ["hello-world.cc"],
  9. deps = [
  10. ":hello-greet",
  11. ],
  12. )

构建项目

  1. cd cpp-tutorial/stage2
  2. bazel build //main:hello-world

查看依赖图

  1. bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" --output graph

image.png

stage3

多个 package

cpp-tutorial/stage3/libBUILD 文件如下:

  1. cc_library(
  2. name = "hello-time",
  3. srcs = ["hello-time.cc"],
  4. hdrs = ["hello-time.h"],
  5. visibility = ["//main:__pkg__"],
  6. )

cpp-tutorial/stage3/mainBUILD 文件如下:

  1. cc_library(
  2. name = "hello-greet",
  3. srcs = ["hello-greet.cc"],
  4. hdrs = ["hello-greet.h"],
  5. )
  6. cc_binary(
  7. name = "hello-world",
  8. srcs = ["hello-world.cc"],
  9. deps = [
  10. ":hello-greet",
  11. "//lib:hello-time",
  12. ],
  13. )

构建项目

  1. cd cpp-tutorial/stage3
  2. bazel build //main:hello-world

查看依赖图

  1. bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" --output graph

image.png

参考

  1. Introduction to Bazel: Building a C++ Project
  2. bazelbuild github
  3. C/C++ Rules