C++ Bazel project with a Data repository

CAVEAT: it seems this solution does not work under Windows (see comments).

One must create an extra BUILD file in the data directory that defines what data files must be exported. The project structure is now:

├── bin
│   ├── BUILD
│   ├── example.cpp
├── data
│   ├── BUILD
│   └── someData.txt
└── WORKSPACE

This new data/BUILD file is:

exports_files(["someData.txt"])

And the bin/BUILD file is modified to add the someData.txt dependency:

cc_binary(
    name = "example",
    srcs = ["example.cpp"],
    data = ["//data:someData.txt"],
)

Now if you run:

bazel run bin:example

you should get:

INFO: Analysed target //bin:example (2 packages loaded).
INFO: Found 1 target...
Target //bin:example up-to-date:
  bazel-bin/bin/example
INFO: Elapsed time: 0.144s, Critical Path: 0.01s
INFO: Build completed successfully, 3 total actions

INFO: Running command line: bazel-bin/bin/example
Hello_world!

meaning that the example executable has found the data/someData.txt file and printed its content.

Also note that you can use the same scheme for unit testing with

 cc_test(...,data =["//data:someData.txt"], )

You can reproduce this note from this GitHub repo.

Tags:

C++

Bazel