C++ Bazel project with a Data repository

后端 未结 3 1773
被撕碎了的回忆
被撕碎了的回忆 2020-12-18 02:07

I have a (basic) C++ project:

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

where the executable

3条回答
  •  Happy的楠姐
    2020-12-18 02:47

    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.

提交回复
热议问题