Skip to main content
Runfiles are a set of files used by a target at runtime (as opposed to build time). Do not hardcode runfiles paths. Those contain the canonical repository name, but the canonical repository name format is an implementation detail that may change at any time. Use one of the language-specific runfiles libraries to access them: Runfiles are generally referenced by an rlocationpath in the form of $REPO/package/file where $REPO should be the apparent repository name. Most runfiles libraries (see below) support functionality to determine the repository of the currently executed target which is useful to refer to other files in the same repository. Many Bazel rules support Make Variables to translate from a target to an rlocationpath by using the $(rlocationpath //package:target) notation. Examples:
load("@rules_cc//cc:cc_binary.bzl", "cc_binary")

cc_binary(
    name = "runfile",
    srcs = ["runfile.cc"],
    data = ["//examples:runfile.txt"],
    deps = ["@rules_cc//cc/runfiles"],
)
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string>

#include "rules_cc/cc/runfiles/runfiles.h"

using rules_cc::cc::runfiles::Runfiles;

inline constexpr std::string_view someFile = "examples/runfile.txt";

int main(int argc, char **argv) {
  std::string error;
  const auto runfiles = Runfiles::Create(argv[0], BAZEL_CURRENT_REPOSITORY, &error);
  if (runfiles == nullptr) {
    std::cerr << "Failed to create Runfiles object" << error << "\n";
    return 1;
  }

  std::string root = BAZEL_CURRENT_REPOSITORY;
  if (root == "") {
    root = "_main";
  }
  const std::string realPathToSomeFile = runfiles->Rlocation(std::filesystem::path(root) / someFile);

  std::cout << "The content of the runfile is:\n";
  std::ifstream fin(realPathToSomeFile);
  std::string line;
  while (std::getline(fin, line)) {
    std::cout << line << "\n";
  }

  return 0;
}