如何解决 bazel "undeclared inclusion(s)" 错误?

How to resolve bazel "undeclared inclusion(s)" error?

我是 bazel 的新手,我无法使用

构建我的 C++ 包

ERROR: /path/to/package/BUILD:linenumber:1 undeclared inclusion(s) in rule '//path/to/package:name': this rule is missing dependency declarations for the following files included by 'path/to/package/source_file.cpp'

...后跟不同目录中的 header 文件列表。这些文件不是正在构建的包的一部分,而是从其他地方引入的。

我的问题是如何在BUILD文件中正确添加声明来解决错误?

根据在线 Bazel 文档 here 我应该将每个 header 添加到 srcs 列表中。 (需要明确的是,这些是我正在构建的库在内部使用的 header, 而不是 public 接口,所以它们不属于 hdrs。)但如果我尝试这样做,

  srcs = [ ..., "path/to/dependent/headers/header.h",]

我收到一条错误消息

ERROR: ... crosses boundary of subpackage ... (perhaps you meant to put the colon here: ...?)

因为带有 header 的目录不是 Bazel 包。

如果我按照错误消息的建议尝试将最后的 / 更改为冒号,

  srcs = [ ..., "path/to/dependent/headers:header.h",]

然后

ERROR: ... target names may not contain ':'.

Bazel C++ 教程 here,在 "Additonal Include Paths" 部分说外部包含目录应该通过 copts:

声明
cc_library(
    name = "some_lib",
    srcs = ["some_lib.cc"],
    hdrs = ["some_lib.h"],
    copts = ["-Ithird_party/some_lib"],
)

但是添加 -I 标志确实 not git 摆脱了 "undeclared inclusion(s)" 错误!

$ bazel version
Build label: 0.4.3
Build target: bazel-out/local-fastbuild/bin/src/main/java/com/google/devtools/build/lib/bazel/BazelServer_deploy.jar
Build time: Thu Dec 22 12:31:25 2016 (1482409885)
Build timestamp: 1482409885
Build timestamp as int: 1482409885

Bazel 希望您依赖 header(即,将它们放在 deps 中)。基本上,您应该为那些 header 创建一个 cc_library。将 headers 放在 hdrs 中不会公开它们,它只是将它们暴露给依赖于该库的规则(这正是您想要的)。所以你将拥有:

# third_party/some_lib/BUILD
cc_library(
    name = "headers",
    hdrs = glob(["*.h"]),
    visibility = ["//path/to/package:__pkg__"],
)

请注意,您应该将 //path/to/package 替换为实际目标的包,但上面的 __pkg__ 是字面意思:这就是您指示 "visible to that package" 的方式。然后没有其他包可以访问那些 headers.

然后在目标的 deps 中添加 //third_party/some_lib:headers

copts 仅用于修改 C++ 的 header 搜索路径,而不是 Bazel 的。 Bazel 总是假设你会做 #include "path/relative/to/your/workspace/dir.h",但如果你有这样的来源:

#include "foo.h"

其中 foo.h 位于 third_party/some_lib/includes/foo.h,您可以说 copts = ["-Ithird_party/some_lib/includes"] 将其添加到 C++ 的 header 搜索路径。

我遇到了类似的问题"undeclared inclusion(s) in rule",我通过删除 /root/.cache/bazel/ 中的 bazel 缓存文件解决了这个问题。希望有帮助

试试这个,这对我有用

bazel clean --expunge

此命令将清除 Bazel 实例的所有磁盘和内存痕迹。参考:https://docs.bazel.build/versions/main/user-manual.html