9

In my bazel BUILD file, I have a line:

srcs = glob([<pattern1>, <pattern2>, ...])

I tried to have one of my patterns be "../dir/*.cc" but I get an error that I'm not allowed to use the .. sequence here.

Checking the documentation, I have found that it's not permitted, but I'm not sure what the expected substitute is.

Similarly, up-level references (..) and current-directory references (./) are forbidden.

How can I include these other source files in my srcs list given my current file structure? If I can't reference the up-level directory, is there a way to use the package name of the other directory instead?

Apollys supports Monica
  • 2,938
  • 1
  • 23
  • 33

1 Answers1

8

Going "up" from your BUILD file would violate the package boundaries. If you really need that structure and cannot or don't want to change it, you have to make files from one package available to the other package by declaring the corresponding target(s) or at least export the files and making those visible. For instance assuming the following structure:

.
├── BUILD
├── WORKSPACE
├── hello.c
└── tgt
    └── BUILD

It the // (top-level) package BUILD I could say:

filegroup(
    name = "hello",
    srcs = ["hello.c"],
    visibility = ["//tgt:__pkg__"],
)                      

(Could also be: exports_files(["hello.c"], ["//tgt:__pkg__"]) instead in which case I would refer to the file by its name //:hello.c from tgt.)

And inside //tgt (tgt/BUILD) it can then read:

cc_binary(
    name="tgt",
    srcs=["//:hello"],
)                                                                                                                                              

Which would give me:

$ bazel run //tgt
WARNING: /tmp/bzl1/tgt/BUILD:3:10: in srcs attribute of cc_binary rule //tgt:tgt: please do not import '//:hello.c' directly. You should either move the file to this package or depend on an appropriate rule there
INFO: Analyzed target //tgt:tgt (11 packages loaded, 68 targets configured).
INFO: Found 1 target...
Target //tgt:tgt up-to-date:
  bazel-bin/tgt/tgt
INFO: Elapsed time: 0.247s, Critical Path: 0.09s
INFO: 2 processes: 2 linux-sandbox.
INFO: Build completed successfully, 6 total actions
INFO: Build completed successfully, 6 total actions
Hello World!

Note: bazel still flags this as something weird and noteworthy going on. I have to say I do not disagree with it. The tree structure does not seem to correspond to the content very well.

Perhaps in this example the tgt package boundary is artificial and not actually useful? Or hello.c is in the wrong place.

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
  • Thanks for the detailed reply. I also tried using `//` to reference sources from another package and got that same `please do not import '...' directly` warning. Then I decided to use a symlink, are there any downsides or things I should be worried about taking the symlink approach? – Apollys supports Monica Jul 26 '19 at 00:48