下载示例代码
git clone https://github.com/bazelbuild/examples
C++ 代码在 examples/cpp-tutorial 下,目录结构如下:
examples└── cpp-tutorial├──stage1│ ├── main│ │ ├── BUILD│ │ └── hello-world.cc│ └── WORKSPACE├──stage2│ ├── main│ │ ├── BUILD│ │ ├── hello-world.cc│ │ ├── hello-greet.cc│ │ └── hello-greet.h│ └── WORKSPACE└──stage3├── main│ ├── BUILD│ ├── hello-world.cc│ ├── hello-greet.cc│ └── hello-greet.h├── lib│ ├── BUILD│ ├── hello-time.cc│ └── hello-time.h└── WORKSPACE
使用 Bazel 构建
stage1
cpp-tutorial/stage1/main 下 BUILD 文件如下:
cc_binary(name = "hello-world",srcs = ["hello-world.cc"],)
构建项目
cd cpp-tutorial/stage1bazel build //main:hello-world
run
bazel-bin/main/hello-world
查看依赖图
bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" --output graph
可以在 http://viz-js.com/ 查看 graph
stage2
指定多个 target
cpp-tutorial/stage2/main 下 BUILD 文件如下:
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",],)
构建项目
cd cpp-tutorial/stage2bazel build //main:hello-world
查看依赖图
bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" --output graph
stage3
多个 package
cpp-tutorial/stage3/lib 下 BUILD 文件如下:
cc_library(name = "hello-time",srcs = ["hello-time.cc"],hdrs = ["hello-time.h"],visibility = ["//main:__pkg__"],)
cpp-tutorial/stage3/main 下 BUILD 文件如下:
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",],)
构建项目
cd cpp-tutorial/stage3bazel build //main:hello-world
查看依赖图
bazel query --notool_deps --noimplicit_deps "deps(//main:hello-world)" --output graph
