簡體   English   中英

在使用Bazel構建的應用程序中訪問運行時文件

[英]Access runtime files in application built with Bazel

我正在嘗試使用Bazel構建C ++應用程序,該程序在運行時需要大量文件。 我使用構建規則的data屬性將這些文件包括在構建目標中:

cc_binary(
  name = "myapp",
  srcs = [
    "main.cpp",
  ],
  data = glob([ "media/**" ], exclude = [ "media/BUILD", "media/.keep" ]),
)

問題在於,Bazel將運行文件放在一個奇怪的路徑下,即依賴於構建系統的目錄( <build target name>.runfiles/__main__/<build target name>/ )。

除了像這樣硬編碼這些路徑之外,是否有任何其他理智的(或靈活的,如果您願意的話)方式來引用運行文件

// "myapp" is the build target name
FILE* f = fopen("myapp/myapp.runfiles/__main__/myapp/media/file.txt", "r");

還是從清單中讀取路徑(這不是更好的選擇,因為每個文件都以__main__/<build target name>/為前綴)?

除了像這樣硬編碼這些路徑之外,是否有任何其他理智的(或靈活的,如果您願意的話)方式來引用運行文件

還沒。 但是我們正在努力。

有關設計文檔和進度,請參見https://github.com/bazelbuild/bazel/issues/4460

除了László的設計文檔答案之外,您還可以嘗試以下幾種方法:

  1. 使用args屬性告訴二進制文件在哪里。 僅當您通過bazel run運行二進制文件並且要求二進制文件理解這些標志時,這才起作用。

  2. 使用包含所需文件路徑的風格創建清單。 清單將位於已知位置,因此您可以在運行時閱讀該清單。

您可以在此處看到一些示例(它們用於Java,但對於cc規則應該相似):

https://groups.google.com/d/topic/bazel-discuss/UTeGdXjO_lQ/discussion

另一種選擇是使用類似pkg_tar或類似規則的東西,將二進制文件及其運行文件重新打包為所需的任何結構: https ://docs.bazel.build/versions/master/be/pkg.html(據我所知,pkg_tar不會打包二進制文件的運行文件。)

看起來Bazel 0.15 添加了對所謂的Rlocation支持,它允許通過在代碼中添加此類來循環運行時文件:

  1. 依賴於您的構建規則中的以下runfiles庫:

     cc_binary( name = "my_binary", ... deps = ["@bazel_tools//tools/cpp/runfiles"], ) 
  2. 包括運行文件庫。

     #include "tools/cpp/runfiles/runfiles.h" using bazel::tools::cpp::runfiles::Runfiles; 
  3. 創建一個Runfiles對象並使用Rlocation查找運行文件路徑:

     int main(int argc, char** argv) { std::string error; std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error)); // Important: // If this is a test, use Runfiles::CreateForTest(&error). // Otherwise, if you don't have the value for argv[0] for whatever // reason, then use Runfiles::Create(&error). if (runfiles == nullptr) { // error handling } std::string path = runfiles->Rlocation("my_workspace/path/to/my/data.txt"); // ... } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM