本篇文章通过https://github.com/bazelbuild/examples/tree/main/cpp-tutorial里面的例子,来简单介绍下bazel构建的基础知识,方便后续查找和学习。
一、设置工作区:
例子:https://github.com/bazelbuild/examples/tree/main/cpp-tutorial/stage3
编译之前的文件内容:
$ ls // 特别说明:WORKSPACE
README.md WORKSPACE lib main
$ ls lib
BUILD hello-time.cc hello-time.h
$ ls main
BUILD hello-greet.cc hello-greet.h hello-world.cc
设置工作区:新建一个空文件名字叫做WORKSPACE,
如此以来该目录及其内容标识为 Bazel 工作区,并位于项目目录结构的根目录中。
二、构建文件BUILD介绍:
BUILD:一个或多个BUILD
文件,告诉 Bazel 如何构建项目的不同部分,内容如下所示:
$ cat lib/BUILD
load("@rules_cc//cc:defs.bzl", "cc_library")
cc_library(
name = "hello-time",
srcs = ["hello-time.cc"],
hdrs = ["hello-time.h"],
visibility = ["//main:__pkg__"], // 使//lib:hello-time目标 在使用该 属性时对目标lib/BUILD显式可见。这是因为默认情况下,目标仅对同一文件中的其他目标可见。
)
$ cat main/BUILD
load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library")
cc_library( // 编译成lib库
name = "hello-greet",
srcs = ["hello-greet.cc"],
hdrs = ["hello-greet.h"],
)
cc_binary( // 编译成可执行文件
name = "hello-world", // 对应的可执行文件名
srcs = ["hello-world.cc"], // 编译可执行文件所使用的源文件
deps = [ // 编译可执行文件依赖的lib库
":hello-greet", // 表明在当前目录下
"//lib:hello-time", // 表明在lib文件夹下面
],
)
三、构建操作:
$ bazel build //main:hello-world // 构建命令
Starting local Bazel server and connecting to it...
INFO: Analyzed target //main:hello-world (17 packages loaded, 146 targets configured).
INFO: Found 1 target...
Target //main:hello-world up-to-date:
bazel-bin/main/hello-world
INFO: Elapsed time: 15.454s, Critical Path: 1.27s
INFO: 12 processes: 6 internal, 6 darwin-sandbox.
INFO: Build completed successfully, 12 total actions
构建生成的文件:
$ ls
README.md WORKSPACE bazel-bin bazel-out bazel-stage3 bazel-testlogs lib main
$ ls bazel-bin/ // 目标文件
lib main
$ ls bazel-bin/lib
_objs libhello-time.a libhello-time.a-2.params
$ ls bazel-bin/main
_objs hello-world-2.params hello-world.runfiles_manifest libhello-greet.a-2.params
hello-world hello-world.runfiles libhello-greet.a
执行命令:
$ ./bazel-bin/main/hello-world
Hello world
Mon Feb 7 18:19:17 2022
参考文档:
https://docs.bazel.build/versions/4.2.1/skylark/concepts.html