bazel build C ++ projects
bazel project
Use bazel build C ++ projects, the project directory bazel project must contain an empty file WORKSPACE whose existence indicates the root directory of the project is located. BUILD file contains build rules.
Common bazel + c ++ project file structure:
.
├── add.cc
├── add.h
├── BUILD
├── main.cc
└── WORKSPACE
Build a simple project bazel
Build helloworld project:
- hello.cc file as follows:
#include <iostream>
int main()
{
std::cout << "Hello world" << std::endl;
return 0;
}
- BUILD file as follows:
cc_library(
name = "test",
srcs = ["hello.cc"],
)
- name:工程的名字
- srcs:项目的源代码
- Construct
bazel build //:test
//:
Construction of the project is located in the root directory (WORKSPACE directory), test as specified above cc_library name, output is as follows:
INFO: Invocation ID: 4292b15c-ac1c-49d4-9a29-cbeea8cb2852
INFO: Analysed target //:test (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //:test up-to-date:
bazel-bin/libtest.a
bazel-bin/libtest.so
INFO: Elapsed time: 0.062s, Critical Path: 0.00s
INFO: 0 processes.
INFO: Build completed successfully, 1 total action
Output files are stored in the project directory bazel-bin
directory.
Construction of the project include the header file
Project directory as follows:
.
├── add.cc
├── add.h
├── BUILD
├── main.cc
└── WORKSPACE
add.cc file:
#include "add.h"
int add(int a,int b)
{
return a+b;
}
Header add.h:
#ifndef ADD_H_
#define ADD_H_
int add(int a,int b);
#endif
main.cc file:
#include <iostream>
#include "add.h"
int main()
{
int a,b;
std::cin>>a>>b;
std::cout<<a<<"+"<<b<<" = "<<add(a,b);
return 0;
}
Build file:
cc_library(
name = "add",
srcs = ["add.cc"],
hdrs = ["add.h"],
)
cc_binary(
name = "math",
srcs = ["main.cc"],
deps = [
":add"
]
)
Explanation:
- cc_library (name): library file name
- cc_library (srcs): library source files
- Header library files: cc_library (hdrs)
- Name of Project: cc_binary (name)
- cc_binary (srcs): Engineering main code
- cc_binary (deps): dependent libraries
Build the code:
bazel build //:math
View dependency graph:
xdot <(bazel query --nohost_deps --noimplicit_deps 'deps(//:math)' \
--output graph)
The dependency graph as follows:
source code download