当前位置:网站首页>Bazel use tutorial to
Bazel use tutorial to
2022-07-19 10:30:00 【Jiang taiweng】
bazel Use the tutorial
bazel All the code of is in the current project , Every project is a WORKSPACE. Every WORKSPACE There are multiple under package( contain BUILD The folder of files is called package),BUILD Inside are multiple targets, The same package Internal targets Mutually visible by default , Different package Between targets Visibility of requires manual definition , Can be in each package Of BUILD The top of the file declares targets Default visibility to other packages .
One 、 install bazel
Reference resources :Installing Bazel on Ubuntu
sudo apt install curl
curl https://bazel.build/bazel-release.pub.gpg | sudo apt-key add -
echo "deb [arch=amd64] https://storage.googleapis.com/bazel-apt stable jdk1.8" | sudo tee /etc/apt/sources.list.d/bazel.list
sudo apt-get update
sudo apt-get install bazel # install bazel
sudo apt-get install --only-upgrade bazel # upgrade bazel To the latest version
see bazel edition
bazel version
BUILD For building documents "#" Start with a single line comment
Two 、 Compile operation
Reference resources :Command-Line Reference
bazel clean
bazel clean # External dependencies will not be deleted
bazel clean --expunge # Will delete external dependencies
bazel clean --expunge --async
bazel build
bazel build :<exe name> # stay BUILD Where package Execute under directory , Compile the specified target
bazel build :all # Compile the package All under target
bazel build ... # Compile the package All under target
bazel build <//path/to/package>:<exe name> # stay workspace Execute in any directory under ,“//” Express workspace In the directory
bazel build :<exe name> --compilation_mode=dbg # debug mode
bazel build :<exe name> -c dbg # debug mode
bazel build :<exe name> --keep_going # See all the mistakes
bazel build :<exe name> --config=<asan/tsan/msan> # Build the project with sanitizers by adding the --config=<asan/tsan/msan> build flag to select AddressSanitizer (asan), ThreadSanitizer (tsan) or MemorySanitizer (msan) accordingly.
bazel build :<exe name> --config local_first
bazel run
bazel run :<target name>
bazel run -- :<target name>
There is no need to execute build, In execution run,run Will automatically first build Re execution
bazel test
bazel test:<target name>
working principle
Loading and target Relevant BUILD file
analysis inputs and dependencies, Generate action graph
perform graph, Produce outputs
action graph: bazel Rely on this graph to track file changes , And whether you need to recompile , And it can also provide users with dependency diagrams between codes .
bazel query 'deps(//<path_to_package>:<target_name>)' # see target Dependence
bazel query "somepath(//<path_to_package>:<target1_name>,//<path_to_package>:<target2_name>)"
3、 ... and 、WORKSPACE file
Reference resources :Working with external dependencies
WORKSPACE The file is mainly named workspace And declare external dependencies , This includes the acquisition methods and acquisition methods of external dependencies .WORKSPACE File tell Bazel How to get other engineering sources , then package Medium BUILD The document can be based on WORKSPACE The outside of target Name dependency .WORKSPACE Files allow users to rely on the goals of other file systems or downloaded from the Internet . In addition to bazel build It can automatically obtain external dependencies , You can also use bazel fetch To obtain a .Bazel Will cache external dependencies , And only in WORKSPACE Download and update again after the file is changed .WORKSPACE The syntax and BUILD The documents are consistent , However, some specific built-in rule. All external dependencies will be downloaded to a soft connection directory named . The specific content can be obtained through the command line :
ls $(bazel info output_base)/external
There are three main types of external dependencies :
1、 Depend on others Bazel engineering
According to this Bazel The location of the project is different , Call different built-in rule To obtain a :
local_repository: Local
git_repository:git Warehouse
http_archive: Download Online
2、 Rely on other non Bazel engineering
There is another case that another project is not Bazel engineering , Then you need another way to add dependent references
new_local_repository: Local
new_git_repository:git Warehouse
new_http_archive: Download Online
3、 Rely on external packages
Maven Warehouse :Use the rule maven_jar (and optionally the rule maven_server) to download a jar from a Maven repository and make it available as a Java dependency.
Workspace Rules
Reference resources :C / C++ Rules
bind
bind(name, actual, compatible_with, deprecation, distribs, features, licenses, restricted_to, tags, testonly, visibility)
to target Life alias , It is not recommended to use
git_repository
git_repository(name, commit, init_submodules, remote, sha256, tag)
This has many restrictions and is not recommended , use http_archive Instead of making it more robust and safe .
http_archive
http_archive(name, sha256, strip_prefix, type, url, urls)
Download a compressed format Bazel Warehouse , And extract it , Then bind and use . This Rule There is an attribute strip_prefix, Used to eliminate prefix directories .
give an example :
(1) glog / gflags
Directory structure
├── WORKSPACE
├── BUILD
└── main.cc
WORKSPACE
workspace(name = "bazel_test")
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
git_repository(
name = "com_github_gflags_gflags",
commit = "f7388c6655e699f777a5a74a3c9880b9cfaabe59",
remote = "https://github.com/gflags/gflags.git",
)
git_repository(
name = "glog",
commit = "0a2e5931bd5ff22fd3bf8999eb8ce776f159cda6",
remote = "https://github.com/google/glog.git",
)
BUILD
cc_binary(
name = "bazel_test",
srcs = ["main.cc"],
deps = [
"@com_github_gflags_gflags//:gflags",
"@glog",
],
)
main.cc
#include <glog/logging.h>
#include <gflags/gflags.h>
DEFINE_string(name, "alan", "your name");
int main(int argc, char *argv[]) {
google::InitGoogleLogging(argv[0]);
FLAGS_logtostderr = 1;
FLAGS_colorlogtostderr = 1;
gflags::ParseCommandLineFlags(&argc, &argv, true);
LOG(INFO) << "hello " << FLAGS_name;
return 0;
}
perform
bazel run -- :bazel_test --name alan
(2) gtest
Directory structure
├── WORKSPACE
├── gtest.BUILD
├── main.cc
└── BUILD
WORKSPACE
workspace(name = "bazel_test")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "gtest",
url = "https://github.com/google/googletest/archive/release-1.7.0.zip",
sha256 = "b58cb7547a28b2c718d1e38aee18a3659c9e3ff52440297e965f5edffe34b6d0",
build_file = "@//:gtest.BUILD",
strip_prefix = "googletest-release-1.7.0",
)
gtest.BUILD
cc_library(
name = "main",
srcs = glob(
["src/*.cc"],
exclude = ["src/gtest-all.cc"]
),
hdrs = glob([
"include/**/*.h",
"src/*.h"
]),
copts = ["-Iexternal/gtest/include"],
linkopts = ["-pthread"],
visibility = ["//visibility:public"],
)
BUILD
cc_test(
name = "bazel_test",
srcs = ["main.cc"],
copts = ["-Iexternal/gtest/include"],
deps = [
"@gtest//:main",
],
)
main.cc
#include "gtest/gtest.h"
int abs(int x) {
return x >= 0? x : -x;
}
TEST(BazelTest, AbsTest) {
EXPECT_EQ(abs(-1), 1);
}
perform
bazel test :bazel_test
Reference resources :Introduction to Bazel: Common C++ Build Use Cases
(3) proto
Directory structure
├── WORKSPACE
├── BUILD
├── main.cc
└── foo.proto
WORKSPACE
workspace(name = "bazel_test")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "rules_proto",
sha256 = "602e7161d9195e50246177e7c55b2f39950a9cf7366f74ed5f22fd45750cd208",
strip_prefix = "rules_proto-97d8af4dc474595af3900dd85cb3a29ad28cc313",
urls = [
"https://mirror.bazel.build/github.com/bazelbuild/rules_proto/archive/97d8af4dc474595af3900dd85cb3a29ad28cc313.tar.gz",
"https://github.com/bazelbuild/rules_proto/archive/97d8af4dc474595af3900dd85cb3a29ad28cc313.tar.gz",
],
)
load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains")
rules_proto_dependencies()
rules_proto_toolchains()
BUILD
#load("@rules_cc//cc:defs.bzl", "cc_proto_library")
#load("@rules_proto//proto:defs.bzl", "proto_library")
cc_binary(
name = "bazel_test",
srcs = ["main.cc"],
deps = [":foo_cc_proto"],
)
proto_library(
name = "foo_proto",
srcs = [
"foo.proto",
],
)
cc_proto_library(
name = "foo_cc_proto",
deps = [
":foo_proto",
],
)
main.cc
#include "foo.pb.h"
int main(int argc, char *argv[]) {
foo::Bar bar;
bar.set_id(10);
std::cout << "id: " << bar.id() << std::endl;
return 0;
}syntax = "proto3";
package foo;
message Bar {
int32 id = 1;
}
perform
bazel run :bazel_test
Reference resources :GitHub - bazelbuild/rules_proto: Protocol buffer rules for Bazel
(4) eigen
Directory structure
├── WORKSPACE
├── BUILD
└── main.cc
WORKSPACE
workspace(name = "bazel_test")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
http_archive(
name = "com_github_eigen_eigen",
sha256 = "dd254beb0bafc695d0f62ae1a222ff85b52dbaa3a16f76e781dce22d0d20a4a6",
strip_prefix = "eigen-eigen-5a0156e40feb",
urls = [
"http://bitbucket.org/eigen/eigen/get/3.3.4.tar.bz2",
],
build_file_content =
"""
cc_library(
name = 'eigen',
srcs = [],
includes = ['.'],
hdrs = glob(['Eigen/**']),
visibility = ['//visibility:public'],
)
"""
)
BUILD
cc_binary(
name = "bazel_test",
srcs = ["main.cc"],
deps = [
"@com_github_eigen_eigen//:eigen",
],
)
main.cc
#include <iostream>
#include <Eigen/Dense>
int main(int argc, char *argv[])
{
Eigen::Matrix3d m = Eigen::Matrix3d::Identity();
std::cout << m << std::endl;
return 0;
}
perform
bazel run :bazel_test
(5) ceres ( rely on gflags、glog、eigen、benchmark)
Directory structure
├── WORKSPACE
├── BUILD
└── main.cc
WORKSPACE
workspace(name = "bazel_test")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
# External dependency: Google Flags; has Bazel build already.
http_archive(
name = "com_github_gflags_gflags",
sha256 = "6e16c8bc91b1310a44f3965e616383dbda48f83e8c1eaa2370a215057b00cabe",
strip_prefix = "gflags-77592648e3f3be87d6c7123eb81cbad75f9aef5a",
urls = [
"https://mirror.bazel.build/github.com/gflags/gflags/archive/77592648e3f3be87d6c7123eb81cbad75f9aef5a.tar.gz",
"https://github.com/gflags/gflags/archive/77592648e3f3be87d6c7123eb81cbad75f9aef5a.tar.gz",
],
)
# External dependency: Google Log; has Bazel build already.
http_archive(
name = "com_github_google_glog",
sha256 = "7083af285bed3995b5dc2c982f7de39bced9f0e6fd78d631f3285490922a0c3d",
strip_prefix = "glog-3106945d8d3322e5cbd5658d482c9ffed2d892c0",
urls = [
"https://github.com/drigz/glog/archive/3106945d8d3322e5cbd5658d482c9ffed2d892c0.tar.gz",
],
)
# External dependency: Eigen; has no Bazel build.
http_archive(
name = "com_github_eigen_eigen",
sha256 = "dd254beb0bafc695d0f62ae1a222ff85b52dbaa3a16f76e781dce22d0d20a4a6",
strip_prefix = "eigen-eigen-5a0156e40feb",
urls = [
"http://bitbucket.org/eigen/eigen/get/3.3.4.tar.bz2",
],
build_file_content =
"""
# TODO(keir): Replace this with a better version, like from TensorFlow.
# See https://github.com/ceres-solver/ceres-solver/issues/337.
cc_library(
name = 'eigen',
srcs = [],
includes = ['.'],
hdrs = glob(['Eigen/**']),
visibility = ['//visibility:public'],
)
"""
)
# External dependency: Google Benchmark; has no Bazel build.
http_archive(
name = "com_github_google_benchmark",
urls = ["https://github.com/google/benchmark/archive/56f52ee228783547f544d9ac4a533574b9010e3f.zip"],
sha256 = "8c1c6e90cd320b07504fabb86400f390faff2e599183ebd9396908817968ae79",
strip_prefix = "benchmark-56f52ee228783547f544d9ac4a533574b9010e3f",
build_file_content =
"""
cc_library(
name = "benchmark",
srcs = glob([
"src/*.h",
"src/*.cc",
]),
hdrs = glob(["include/benchmark/*.h"]),
copts = [
"-DHAVE_STD_REGEX",
],
includes = [
"include",
],
visibility = ["//visibility:public"],
)
"""
)
local_repository(
name = "ceres",
path = "/home/alan/3rdparty/ceres-solver-1.14.0",
)
BUILD
cc_binary(
name = "bazel_test",
srcs = ["main.cc"],
deps = [
"@ceres",
],
)
main.cc
#include <iostream>
#include <Eigen/Dense>
int main(int argc, char *argv[])
{
Eigen::Matrix3d m = Eigen::Matrix3d::Identity();
std::cout << m << std::endl;
return 0;
}
perform
bazel run :bazel_test
Reference resources :
Non-linear Least Squares — Ceres Solver
https://ceres-solver.googlesource.com/ceres-solver/+/master/WORKSPACE
(6) opencv
Link local compilation and installation opencv library
git clone https://github.com/opencv/opencv.git
cd opencv/
mkdir build install
cd build
cmake -D CMAKE_BUILD_TYPE=Release -D CMAKE_INSTALL_PREFIX=/home/alan/3rdparty/opencv/install ..
make install
Directory structure
├── WORKSPACE
├── opencv.BUILD
├── main.cc
└── BUILD
WORKSPACE
workspace(name = "bazel_test")
new_local_repository(
name = "opencv",
path = "/home/alan/3rdparty/opencv/install",
build_file = "opencv.BUILD",
)
opencv.BUILD
cc_library(
name = "opencv",
srcs = glob(["lib/*.so*"]),
hdrs = glob(["include/**/*.hpp"]),
includes = ["include"],
visibility = ["//visibility:public"],
linkstatic = 1,
)
BUILD
cc_binary(
name = "bazel_test",
srcs = ["main.cc"],
deps = [
"@opencv//:opencv",
],
)
main.cc
#include <opencv2/opencv.hpp>
int main(int argc, char *argv[]) {
cv::Mat img = cv::imread("/home/alan/1.jpg");
std::cout << "Resolution: " << img.rows << " x " << img.cols << std::endl;
return 0;
}
perform
bazel run :bazel_test
Reference resources :Building OpenCV code using Bazel
tf_cc_binary: Object file Compilation Rules , As a binary executable .name Must be unique ,srcs Specifies the source file ,linkopts Link rules specified ,deps The dependent file is specified
cc_library: Library file Compilation Rules ,name Specifies the file name after compiling as a library file ,srcs and hdrs Specify source and header files ,deps Specify other files to rely on
tf_cc_test: Test file rules
package: Common methods , The defined value will apply to each of the following children rule in .default_visibility Specifies the default visibility rule for this package . Can only be seen by other package call .
licenses: Common methods , default license
load: Common methods , load .bzl file
filegroup: Common methods , For multiple compilation targets target Specify a name ,glob Is a help function , Specifies which files in the directory will include, Which will exclude.visibility It specifies target The visibility of , That is, what can be package call
name Attribute to name rules ,
deps Attribute to describe the dependencies between rules . Use colons to separate package names from rule names . If the rule that a rule depends on is in another directory , Just use "//" start , If it's in the same directory , You can ignore the package name and start with a colon .
linkopts Link rules specified
边栏推荐
- Studio 3T无限试用
- HCIA 复习作答 2022.7.6
- R语言使用R原生函数进行数据聚合统计(Aggregating transforms)计算滑动窗口统计值(Window Statistics)、计算滑动分组最小值(min)并合并生成的统计数据到原数据集
- 图神经网络的可解释性方法介绍和GNNExplainer解释预测的代码示例
- Software engineering - ranking of majors in Chinese Universities of Software Science
- STL中stack和queue的使用以及模拟实现
- 高性能IO框架库libevent(三):libevent框架函数概述
- Ffmpeg record video, stop (vb.net, step on the pit, class library - 10)
- STM32F407 NVIC
- 日期——贵州大学考研机试题目
猜你喜欢

如何解决谷歌浏览器解决跨域访问的问题

JMeter中如何实现接口之间的关联?

荔枝音质高保真AI降噪技术分享

FFmpeg录制视频、停止(VB.net,踩坑,类库——10)

圆桌实录:炉边对话——如何在 Web3 实现创新

Kirin Xin'an operating system derivative solution | host security reinforcement software, to achieve one click rapid reinforcement!

为什么磁力变速齿轮会反转?

中科磐云—D模块web远程代码执行漏洞解析

Excel表格转换为Word表格,并且保留Excel表格中公式不发生变化

Go to school = earn money? Immortal college without paying tuition fees!
随机推荐
王者荣耀商城异地多活架构设计
Effectively understand FreeSQL wheredynamicfilter and deeply understand the original design intention [.net orm]
C语言自定义类型详解
MFC|框架下自绘CEdit控件
Laravel generate sub table script example
微信小程序云开发 1 - 数据库
vim怎么保存后退出
Quick completion guide of manipulator (XIII): joint space trajectory planning
How to save and exit VIM
String类型函数传递问题
Blender digital twin production tutorial
How to realize the association between interfaces in JMeter?
基于微信小程序的外卖点餐系统
A multidimensional sequence anomaly detection method based on Grubbs and isolated forest
ash: /etc/apt/sources. List: insufficient permissions
笔记本键盘失灵解决办法
中职网络安全——(2022网络安全nc批量连接的脚本)免费的脚本哦~~~
Zhongke Panyun - Cyberspace Security packet capture topic b.pcap
2022年湖南省中职组“网络空间安全”数据包分析infiltration.pacpng解析(超详细)
Excel表格转换为Word表格,并且保留Excel表格中公式不发生变化