我有一个(基本的)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设置是最小的设置:
cc_binary(name = "example",srcs = ["example.cpp"])
Hello_world!
行问题在于Bazel将所有这些文件移动到特殊位置:
.
├── bazel-Bazel_with_Data -> ...
├── bazel-bin -> ...
├── bazel-genfiles -> ...
├── bazel-out -> ...
├── bazel-testlogs -> ...
奇怪的是,示例可执行文件找不到 data / someData.txt 文件:
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 / someData.txt 文件。
答案 0 :(得分:1)
CAVEAT:似乎此解决方案在Windows下无效(请参阅评论)。
必须在数据目录中创建一个额外的 BUILD 文件,该文件定义必须导出哪些数据文件。项目结构现在是:
├── bin
│ ├── BUILD
│ ├── example.cpp
├── data
│ ├── BUILD
│ └── someData.txt
└── WORKSPACE
这个新的 data / BUILD 文件是:
exports_files(["someData.txt"])
修改 bin / BUILD 文件以添加 someData.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 / someData.txt 文件并打印其内容。
另请注意,您可以将单元测试与
一起使用相同的方案 cc_test(...,data =["//data:someData.txt"], )
您可以从此GitHub repo重现此记事。
答案 1 :(得分:1)
在Windows上尝试:
bazel run --enable_runfiles
更多详细信息,请参见here。
您还可以将其添加到.bazelrc
文件中:
build:myconfig --enable_runfiles
以这种方式在Windows上构建:
bazel build --config=myconfig //...
还可以选择运行文件库。
答案 2 :(得分:0)