C++ Bazel project with a Data repository

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

I have a (basic) C++ project:

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

where the executable

相关标签:
3条回答
  • 2020-12-18 02:27

    On Windows try:

    bazel run --enable_runfiles
    

    More details can be found here.

    You can add this also to a .bazelrc file:

    build:myconfig --enable_runfiles
    

    An build on Windows this way:

    bazel build --config=myconfig //...
    

    Also the runfile lib is an option.

    0 讨论(0)
  • 2020-12-18 02:31

    I posted the issue to bazel issues. It was recommended to use Runfiles to extract the absolute path from the relative path. Then you should be able to plug in the path to ifstream. It should be noted that your relative path needs to be prepended by "__main__"

    std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
    std::string path = runfiles->Rlocation("__main__/relative_path");
    std::ifstream in(path);
    

    Documentation on Runfiles Usage: LINK

    GITHUB ISSUE HERE: LINK

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题