使用bazel run运行cc_binary时未覆盖输出文件的问题咨询
问题分析与解决
- 这并非Bazel配置遗漏,核心原因是你的C++程序本身未处理文件覆盖逻辑。Bazel执行
bazel run时仅负责编译并启动程序,文件写入行为完全由代码自身控制。 - 若要实现无论
out.txt是否存在都覆盖写入,需修改代码逻辑:- 使用
std::ofstream时,确保指定std::ios::trunc标志(若代码用了std::ios::app等追加模式,会导致不覆盖已有内容) - 示例代码:
#include <fstream> int main() { // 显式指定trunc确保覆盖已有文件 std::ofstream outfile("out.txt", std::ios::out | std::ios::trunc); if (outfile.is_open()) { outfile << "输出内容\n"; outfile.close(); } return 0; }
- 使用
- 补充:
bazel run的默认工作目录是Bazel运行时沙箱,若需将输出文件放到bazel-bin这类Bazel输出目录,可通过$(location)宏传递路径:- BUILD文件修改:
cc_binary( name = "my_prog", srcs = ["my_prog.cpp"], args = ["$(location out.txt)"], outputs = ["out.txt"], ) - 程序接收命令行参数作为输出路径:
#include <fstream> #include <string> int main(int argc, char* argv[]) { if (argc < 2) return 1; std::string out_path = argv[1]; std::ofstream outfile(out_path, std::ios::out | std::ios::trunc); if (outfile.is_open()) { outfile << "输出内容\n"; outfile.close(); } return 0; }
- BUILD文件修改:
内容的提问来源于stack exchange,提问作者Curious
相关产品推荐
相关产品推荐

