bazel的使用
bazel是google開源的構建工具,可以支持多種語言的構建。這里來嘗試一下如何在C++項目中使用bazel構建。
安裝就不介紹了,在官網很詳細,輸入bazel --help:
Usage: bazel <command> <options> ...
Available commands:
analyze-profile Analyzes build profile data.
build Builds the specified targets.
canonicalize-flags Canonicalizes a list of bazel options.
clean Removes output files and optionally stops the server.
coverage Generates code coverage report for specified test targets.
dump Dumps the internal state of the bazel server process.
fetch Fetches external repositories that are prerequisites to the targets.
help Prints help for commands, or the index.
info Displays runtime info about the bazel server.
license Prints the license of this software.
mobile-install Installs targets to mobile devices.
query Executes a dependency graph query.
run Runs the specified target.
shutdown Stops the bazel server.
test Builds and runs the specified test targets.
version Prints version information for bazel.
看上去和maven差不太多,以一個實際項目來介紹一下基本命令的使用。
bazel build
在目錄下建立test文件夾和WORKSPACE,並在test下創建兩個文件,分別如下:
├── test
│ ├── BUILD
│ └── test.cc
└── WORKSPACE
內容如下:
BUILD:
package(default_visibility = ["//visibility:public"])
cc_binary(
name = "test",
srcs = [
"test.cc",
],
)
WORKSPACE為空
test.cc:
#include <iostream>
int main()
{
std::cout<<"test"<<std::endl;
return 0;
}
其中:WORKSPACE和BUILD是bazel項目必須的文件,test.cc是我們自己定義的c++文件,.cc后綴是unix系統的后綴,.cpp是非unix系統。
構建項目
在test/目錄下執行以下命令可以編譯c++文件:
bazel build [target]
本例中:
bazel build test/...
注意是3個點!
編譯成功的結果:
INFO: Analysed target //test:test (0 packages loaded).
INFO: Found 1 target...
Target //test:test up-to-date:
bazel-bin/test/test
INFO: Elapsed time: 0.219s, Critical Path: 0.01s
INFO: Build completed successfully, 1 total action
目錄結果變為:
├── bazel-bin -> /home/mobvoi/.cache/bazel/_bazel_mobvoi/74778f1ed6b087a47652b1c57f0f5d45/execroot/__main__/bazel-out/local-fastbuild/bin
├── bazel-genfiles -> /home/mobvoi/.cache/bazel/_bazel_mobvoi/74778f1ed6b087a47652b1c57f0f5d45/execroot/__main__/bazel-out/local-fastbuild/genfiles
├── bazel-out -> /home/mobvoi/.cache/bazel/_bazel_mobvoi/74778f1ed6b087a47652b1c57f0f5d45/execroot/__main__/bazel-out
├── bazel-test -> /home/mobvoi/.cache/bazel/_bazel_mobvoi/74778f1ed6b087a47652b1c57f0f5d45/execroot/__main__
├── bazel-testlogs -> /home/mobvoi/.cache/bazel/_bazel_mobvoi/74778f1ed6b087a47652b1c57f0f5d45/execroot/__main__/bazel-out/local-fastbuild/testlogs
├── test
│ ├── BUILD
│ └── test.cc
└── WORKSPACE
在bazel-bin/test/test.runfiles/main/test目錄下有二進制文件,運行:
$ ./test
test
至此bazel編譯成功!
bazel run
bazel build用來編譯cpp為二進制文件,除此之外還可以直接運行cpp文件中的main函數。
bazel query
用來查看依賴樹。
bazel test
類似mvn test,運行代碼中的單測。
bazel clean
清除編譯的結果,類似mvn clean。