带有数据存储库的C Bazel项目

C++ Bazel project with a Data repository

本文关键字:Bazel 项目 数据 存储      更新时间:2023-10-16

我有一个(基本)C 项目:

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

其中可执行文件 example.cpp 使用data/目录中的一些数据文件:

#include <fstream>
#include <iostream>
int main()
{
  std::ifstream in("data/someData.txt");
  if (!in)
  {
    std::cerr << "Can not open file!";
    return EXIT_FAILURE;
  }
  std::string message;
  if (!(in >> message))
  {
    std::cerr << "Can not read file content!";
    return EXIT_FAILURE;
  }
  std::cout << message << std::endl;
  return EXIT_SUCCESS;
}

我的Bazel设置是最小的:

  • 工作区:空文件
  • bin/build cc_binary(name = "example",srcs = ["example.cpp"])
  • data/ymedata.txt :包含Hello_world!

问题是Bazel在特殊位置移动所有这些文件:

.
├── bazel-Bazel_with_Data -> ...
├── bazel-bin -> ...
├── bazel-genfiles -> ...
├── bazel-out -> ...
├── bazel-testlogs -> ...

在特殊的示例可执行文件中找不到 data/ymedata.txt file:

bazel run bin:example

将打印:

INFO: Analysed target //bin:example (0 packages loaded).
INFO: Found 1 target...
Target //bin:example up-to-date:
  bazel-bin/bin/example
INFO: Elapsed time: 0.101s, Critical Path: 0.00s
INFO: Build completed successfully, 1 total action
INFO: Running command line: bazel-bin/bin/example
Can not open file!ERROR: Non-zero return code '1' from command: Process exited with status 1

问题是如何管理?

我想要示例可执行文件能够找到 data/ymedata.txt file。

caveat:似乎在Windows下此解决方案不起作用(请参阅注释)。

必须在 data 目录中创建一个额外的 build 文件,该文件定义了必须导出的数据文件。现在的项目结构是:

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

这个新的数据/构建文件是:

exports_files(["someData.txt"])

bin/build 文件已修改以添加 ymedata.txt 依赖关系:

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

现在运行:

bazel run bin:example

您应该得到:

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!

表示示例可执行文件找到 data/ymedata.txt 文件并打印了其内容。

还要注意,您可以使用单元测试的相同方案

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

您可以从此GitHub仓库中复制此注释。

在Windows上尝试:

bazel run --enable_runfiles

可以在此处找到更多详细信息。

您也可以将其添加到.bazelrc文件:

build:myconfig --enable_runfiles

以这种方式在窗户上构建:

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

也是Runfile lib的选项。

我将问题发布给了巴泽尔问题。建议使用Runfiles从相对路径中提取绝对路径。然后,您应该能够插入通往ifstream的路径。应该注意的是,您的相对路径需要由__main__

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

请参阅runfiles用法上的文档。

github发行