如何在Bazel中包含上级参考?

时间:2019-08-02 16:52:12

标签: bazel

我是Bazel的新手(0.28.1版)。 如何在另一个目录中包含头文件?下面的目录结构代表了我的问题。

.
├── WORKSPACE
├── src
│   ├── Makefile
│   ├── hellomake.c
│   ├── hellofunc.c
│   └── BUILD
└── include
    └── hellomake.h

使用src中的Makefile可以很好地构建树。但是,使用Make可以使用“ -I ../include”引用包含文件。当我尝试使用Bazel构建同一棵树时,我无法成功包含头文件hellomake.h。显然,上级引用“ ..”不起作用。

我的构建文件:

cc_library (
    name = "hellomake",
    srcs = ["hellomake.c"],
    hdrs = ["//include/hellomake.h"],
    copts = ["-I include"],
)

cc_library (
    name = "hellofunc",
    srcs = ["hellofunc.c"],
    hdrs = ["//include/hellomake.h"],
    copts = ["-I include"],
)

cc_binary(
    name = "hello",
    deps = [ ":hellomake", ":hellofunc", ],
)

来自“。”我的命令是:

bazel build //src/hello

1 个答案:

答案 0 :(得分:1)

直接的答案是,您不能仅跨越包装边界。包是工作空间目录树中具有其BUILD文件的每个节点,因此最小的更改将是使带有源和标头的树成为一个包(将BUILD向上移动一个目录)并将其读取像这样:

cc_library (
    name = "hellomake",
    srcs = ["src/hellomake.c"],
    hdrs = ["include/hellomake.h"],
    copts = ["-I include"],
)

cc_library (
    name = "hellofunc",
    srcs = ["src/hellofunc.c"],
    hdrs = ["include/hellomake.h"],
    copts = ["-I include"],
)

cc_binary(
    name = "hello",
    deps = [ ":hellomake", ":hellofunc", ],
)

然后您可以构建:

bazel build //:hello

但是我怀疑这里还有更多需要打开的东西。根据{{​​1}}规则的链接顺序(deps),我怀疑cc_binary实际上不是一个库,而是它自己的hellomake.c的二进制源,并且因此:

  • 可以直接这样声明
  • main()实际上是hellomake.h的接口,应相应命名

基于此假设,hellofunc.c文件现在看起来像这样:

BUILD

现在,如果您实际上想将源代码和标头用作单独的包,则可以这样做,但是您必须在cc_library ( name = "hellofunc", srcs = ["src/hellofunc.c"], hdrs = ["include/hellofunc.h"], includes = ["include"], ) cc_binary ( name = "hello", srcs = ["src/hellomake.c"], deps = [":hellofunc"], ) 包中将标头文件声明为cc_library将其放入//include

./include/BUILD

然后在cc_library ( name = "hellofunc_hdr", hdrs = ["hellofunc.h"], includes = ["."], visibility = ["//src:__pkg__"], ) //src)中,您可以说:

./src/BUILD

这样您就可以运行cc_library ( name = "hellofunc", srcs = ["hellofunc.c"], deps = ["//include:hellofunc_hdr"], ) cc_binary ( name = "hello", srcs = ["hellomake.c"], deps = [":hellofunc"], )

诚然,这看起来有些奇怪,而且这种包装似乎并未传达出很多有意义的结构,因此也许我们最终可能将hellofunc(库)作为一个(bazel build //src:hello)包装,并以hellomake作为我们的来源二进制(func)。这棵树看起来像这样:

hello

. ├── WORKSPACE ├── func │   ├── BUILD │   ├── hellofunc.c │   └── hellofunc.h └── hello ├── BUILD └── hellomake.c 中的BUILD文件可以是:

./func/

使用cc_library ( name = "func", srcs = ["hellofunc.c"], hdrs = ["hellofunc.h"], includes = ["."], visibility = ["//hello:__pkg__"], ) 中的

./hello/

然后我们可以运行cc_binary ( name = "hello", srcs = ["hellomake.c"], deps = ["//func"], )