Including multiple files in a target
You can include multiple files in a single target with glob. For example:.cc and .h files it finds in the
same directory as the BUILD file that contains this target (excluding
subdirectories).
Using transitive includes
If a file includes a header, then any rule with that file as a source (that is, having that file in thesrcs, hdrs, or textual_hdrs attribute) should
depend on the included header’s library rule. Conversely, only direct
dependencies need to be specified as dependencies. For example, suppose
sandwich.h includes bread.h and bread.h includes flour.h. sandwich.h
doesn’t include flour.h (who wants flour in their sandwich?), so the BUILD
file would look like this:
sandwich library depends on the bread library, which depends
on the flour library.
Adding include paths
Sometimes you cannot (or do not want to) root include paths at the workspace root. Existing libraries might already have an include directory that doesn’t match its path in your workspace. For example, suppose you have the following directory structure:some_lib.h to be included as
legacy/some_lib/include/some_lib.h, but suppose some_lib.cc includes
"some_lib.h". To make that include path valid,
legacy/some_lib/BUILD will need to specify that the some_lib/include
directory is an include directory:
/ prefix.
Including external libraries
Suppose you are using Google Test. You can use one of the repository functions in theWORKSPACE file to
download Google Test and make it available in your repository:
BUILD file, you can leave
out the build_file attribute.
Then create gtest.BUILD, a BUILD file used to compile Google Test.
Google Test has several “special” requirements that make its cc_library rule
more complicated:
-
googletest-release-1.10.0/src/gtest-all.cc#includes all other files ingoogletest-release-1.10.0/src/: exclude it from the compile to prevent link errors for duplicate symbols. -
It uses header files that are relative to the
googletest-release-1.10.0/include/directory ("gtest/gtest.h"), so you must add that directory to the include paths. -
It needs to link in
pthread, so add that as alinkopt.
googletest-release-1.10.0
as a byproduct of the archive’s structure. You can make http_archive strip
this prefix by adding the strip_prefix attribute:
gtest.BUILD would look like this:
cc_ rules can depend on @gtest//:main.
Writing and running C++ tests
For example, you could create a test./test/hello-test.cc, such as:
./test/BUILD file for your tests:
hello-greet visible to hello-test, you must add
"//test:__pkg__", to the visibility attribute in ./main/BUILD.
Now you can use bazel test to run the test.
Adding dependencies on precompiled libraries
If you want to use a library of which you only have a compiled version (for example, headers and a.so file) wrap it in a cc_library rule: