I have started using Bazel and ran into some behaviour which felt strange to me considering the documentation.
Consider the following example BUILD file:
cc_binary(
name = "hello-world",
srcs = ["hello-world.cc"],
deps = [":hello"]
)
cc_library(
name = "hello",
hdrs = ["hello.h"],
srcs = ["hello.cc"],
deps = [":dep"]
)
cc_library(
name = "dep",
srcs = ["dep.h"],
)
In hello-world.cc I include dep.h using #include "dep.h".
I was suprised that running bazel build on //:hello-world succeeded because my expectation would have been that:
a) I cannot include dep.h in any other library than dep since I declared it in srcs and the documentation implies that it therefore is not visible anywhere else as written here:
https://bazel.build/reference/be/c-cpp#cc_library
For cc_library rules, headers in hdrs comprise the public interface of the library and can be directly included both from the files in hdrs and srcs of the library itself as well as from files in hdrs and srcs of cc_* rules that list the library in their deps. Headers in srcs must only be directly included from the files in hdrs and srcs of the library itself. When deciding whether to put a header into hdrs or srcs, you should ask whether you want consumers of this library to be able to directly include it. This is roughly the same decision as between public and private visibility in programming languages.
b) Even if it does not matter whether dep.h is declared in hdrs or srcs, dep.h is an actual direct dependency of hello-world.cc but not declared as such. I (perhaps naively) assumed that since Bazel strongly encourages users to declare direct dependencies that it would somehow check for that. In my opinion it's confusing that the :hello library can expose dep.h to :hello-world.
Lastly, if this is all correct and expected behaviour, do you know of some commands that could
- check if all actual direct dependencies have been declared as dependencies in the BUILD file
- check if some of the declared dependencies are unused or indirect dependencies
Thanks in advance, everyone.