Bazel 教學課程:設定 C++ 工具鍊

回報問題 查看原始碼 夜間 7.2 7.1 7.0 6.5 6.4

本教學課程會使用範例情境來說明如何設定 C++ 工具鍊它是根據 C++ 專案範例 使用 clang 建構不會發生錯誤的 API

課程內容

在本教學課程中,您會瞭解如何執行下列作業:

  • 設定建構環境
  • 設定 C++ 工具鍊
  • 建立 Starlark 規則, cc_toolchain 的設定,讓 Bazel 能建構應用程式 合作頻道:clang
  • 執行跑步確認預期結果 Linux 電腦上的 bazel build --config=clang_config //main:hello-world
  • 建構 C++ 應用程式

事前準備

設定建構環境

本教學課程假設您已在 Linux 中,並已成功建立映像檔 C++ 應用程式,並安裝適當的工具和程式庫。 本教學課程使用 clang version 9.0.1,可以在您的系統上安裝。

請按照下列方式設定建構環境:

  1. 如果您還沒有這樣做 下載並安裝 Bazel 0.23 以上版本。

  2. 下載 C++ 專案範例 並存放在本機電腦上的空白目錄。

  3. 將下列 cc_binary 目標新增至 main/BUILD 檔案:

    cc_binary(
        name = "hello-world",
        srcs = ["hello-world.cc"],
    )
    
  4. 使用下列程式碼,在工作區目錄的根目錄中建立 .bazelrc 檔案: 啟用 --config 標記的功能:

    # Use our custom-configured c++ toolchain.
    
    build:clang_config --crosstool_top=//toolchain:clang_suite
    
    # Use --cpu as a differentiator.
    
    build:clang_config --cpu=k8
    
    # Use the default Bazel C++ toolchain to build the tools used during the
    # build.
    
    build:clang_config --host_crosstool_top=@bazel_tools//tools/cpp:toolchain
    

對於 build:{config_name} --flag=value 項目,指令列標記 --config={config_name} 與該標記相關聯。詳情請見 所用標記的說明文件: crosstool_topcpuhost_crosstool_top

建立目標時 搭配 bazel build --config=clang_config //main:hello-world,Bazel 會使用 自訂工具鍊 cc_toolchain_suite //toolchain:clang_suite。套件清單可能會列出不同項目 工具鍊,適用於不同 CPU。 這就是為什麼該與 --cpu=k8 標記有所區別。

因為 Bazel 在建構期間會使用許多以 C++ 編寫的內部工具, 程序包裝函式,會為 因此這些工具是使用該工具鍊建立,而非 來建立值區

設定 C++ 工具鍊

如要設定 C++ 工具鍊,請重複建構應用程式並刪除 每個錯誤 (如下所述)

  1. 使用下列指令執行建構:

    bazel build --config=clang_config //main:hello-world
    

    因為您在--crosstool_top=//toolchain:clang_suite .bazelrc 檔案,Bazel 會擲回下列錯誤:

    No such package `toolchain`: BUILD file not found on package path.
    

    在工作區目錄中,為套件建立 toolchain 目錄 toolchain 目錄中的空 BUILD 檔案。

  2. 再次執行建構。由於 toolchain 套件尚未定義 clang_suite 目標,Bazel 會擲回下列錯誤:

    No such target '//toolchain:clang_suite': target 'clang_suite' not declared
    in package 'toolchain' defined by .../toolchain/BUILD
    

    toolchain/BUILD 檔案中,定義空白檔案群組,如下所示:

    package(default_visibility = ["//visibility:public"])
    
    filegroup(name = "clang_suite")
    
  3. 再次執行建構。Bazel 會擲回下列錯誤:

    '//toolchain:clang_suite' does not have mandatory providers: 'ToolchainInfo'
    

    Bazel 發現 --crosstool_top 標記指向的規則指向 未提供必要的 ToolchainInfo 。因此,您需要將 --crosstool_top 指向提供 ToolchainInfo - 也就是 cc_toolchain_suite 規則。在 toolchain/BUILD 檔案,將空白檔案群組替換為以下內容:

    cc_toolchain_suite(
        name = "clang_suite",
        toolchains = {
            "k8": ":k8_toolchain",
        },
    )
    

    toolchains 屬性會自動對應 --cpu,並 --compiler (如有指定) 的值設為 cc_toolchain。您尚未 如定義任何 cc_toolchain 目標,Bazel 會抱怨 很快就會出現。

  4. 再次執行建構。Bazel 會擲回下列錯誤:

    Rule '//toolchain:k8_toolchain' does not exist
    

    現在,您必須為 cc_toolchain 中的每個值 cc_toolchain_suite.toolchains 屬性。請將下列指令新增至 toolchain/BUILD 檔案:

    filegroup(name = "empty")
    
    cc_toolchain(
        name = "k8_toolchain",
        toolchain_identifier = "k8-toolchain",
        toolchain_config = ":k8_toolchain_config",
        all_files = ":empty",
        compiler_files = ":empty",
        dwp_files = ":empty",
        linker_files = ":empty",
        objcopy_files = ":empty",
        strip_files = ":empty",
        supports_param_files = 0,
    )
    
  5. 再次執行建構。Bazel 會擲回下列錯誤:

    Rule '//toolchain:k8_toolchain_config' does not exist
    

    接下來,請新增 ":k8_toolchain_config"指定 toolchain/BUILD 檔案:

    filegroup(name = "k8_toolchain_config")
    
  6. 再次執行建構。Bazel 會擲回下列錯誤:

    '//toolchain:k8_toolchain_config' does not have mandatory providers:
    'CcToolchainConfigInfo'
    

    CcToolchainConfigInfo 是您用於設定的提供者 C++ 工具鍊。如要修正這項錯誤,請建立 Starlark 規則 將 CcToolchainConfigInfo 提供給 Bazel,方法是 含有以下內容的 toolchain/cc_toolchain_config.bzl 檔案:

    def _impl(ctx):
        return cc_common.create_cc_toolchain_config_info(
            ctx = ctx,
            toolchain_identifier = "k8-toolchain",
            host_system_name = "local",
            target_system_name = "local",
            target_cpu = "k8",
            target_libc = "unknown",
            compiler = "clang",
            abi_version = "unknown",
            abi_libc_version = "unknown",
        )
    
    cc_toolchain_config = rule(
        implementation = _impl,
        attrs = {},
        provides = [CcToolchainConfigInfo],
    )
    

    cc_common.create_cc_toolchain_config_info() 會建立所需的提供者 CcToolchainConfigInfo。如要使用 cc_toolchain_config 規則,請新增載入量 對 toolchains/BUILD 的陳述式:

    load(":cc_toolchain_config.bzl", "cc_toolchain_config")
    

    將「k8_toolchain_config」並將宣告設為 cc_toolchain_config 規則:

    cc_toolchain_config(name = "k8_toolchain_config")
    
  7. 再次執行建構。Bazel 會擲回下列錯誤:

    .../BUILD:1:1: C++ compilation of rule '//:hello-world' failed (Exit 1)
    src/main/tools/linux-sandbox-pid1.cc:421:
    "execvp(toolchain/DUMMY_GCC_TOOL, 0x11f20e0)": No such file or directory
    Target //:hello-world failed to build`
    

    目前 Bazel 擁有充足資訊嘗試建構程式碼, 仍不知道使用哪些工具完成必要建構作業 動作。您必須修改 Starlark 規則的實作,以告知 Bazel 各種實用工具為此,您需要 @bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl

    # toolchain/cc_toolchain_config.bzl:
    # NEW
    load("@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "tool_path")
    
    def _impl(ctx):
        tool_paths = [ # NEW
            tool_path(
                name = "gcc",
                path = "/usr/bin/clang",
            ),
            tool_path(
                name = "ld",
                path = "/usr/bin/ld",
            ),
            tool_path(
                name = "ar",
                path = "/usr/bin/ar",
            ),
            tool_path(
                name = "cpp",
                path = "/bin/false",
            ),
            tool_path(
                name = "gcov",
                path = "/bin/false",
            ),
            tool_path(
                name = "nm",
                path = "/bin/false",
            ),
            tool_path(
                name = "objdump",
                path = "/bin/false",
            ),
            tool_path(
                name = "strip",
                path = "/bin/false",
            ),
        ]
        return cc_common.create_cc_toolchain_config_info(
            ctx = ctx,
            toolchain_identifier = "local",
            host_system_name = "local",
            target_system_name = "local",
            target_cpu = "k8",
            target_libc = "unknown",
            compiler = "clang",
            abi_version = "unknown",
            abi_libc_version = "unknown",
            tool_paths = tool_paths, # NEW
        )
    

    確認 /usr/bin/clang/usr/bin/ld 是正確路徑 。

  8. 再次執行建構。Bazel 會擲回下列錯誤:

     ..../BUILD:3:1: undeclared inclusion(s) in rule '//main:hello-world':
     this rule is missing dependency declarations for the following files included by 'main/hello-world.cc':
     '/usr/include/c++/9/ctime'
     '/usr/include/x86_64-linux-gnu/c++/9/bits/c++config.h'
     '/usr/include/x86_64-linux-gnu/c++/9/bits/os_defines.h'
     ....
    

    Bazel 必須知道要在哪裡搜尋已納入的標頭。另有 解決這個問題,例如使用 includes 屬性 使用 cc_binary,但這裡是在工具鍊層級解決 cxx_builtin_include_directories敬上 cc_common.create_cc_toolchain_config_info 的參數。請注意,如果 您使用的是其他版本的 clang, include 路徑會是 也不一樣這些路徑也可能因分佈情形而異。

    修改 toolchain/cc_toolchain_config.bzl 中的傳回值,以便查看 輸入:

     return cc_common.create_cc_toolchain_config_info(
          ctx = ctx,
          cxx_builtin_include_directories = [ # NEW
            "/usr/lib/llvm-9/lib/clang/9.0.1/include",
            "/usr/include",
          ],
          toolchain_identifier = "local",
          host_system_name = "local",
          target_system_name = "local",
          target_cpu = "k8",
          target_libc = "unknown",
          compiler = "clang",
          abi_version = "unknown",
          abi_libc_version = "unknown",
          tool_paths = tool_paths,
     )
    
  9. 再次執行建構指令,您會看到如下的錯誤:

    /usr/bin/ld: bazel-out/k8-fastbuild/bin/main/_objs/hello-world/hello-world.o: in function `print_localtime()':
    hello-world.cc:(.text+0x68): undefined reference to `std::cout'
    

    這是因為連結器缺少 C++ 標準 而且在程式庫中找不到其符號解決這個問題的方法有很多種 例如使用 cc_binarylinkopts 屬性。解決方法是 確保使用工具鍊的任何目標都不必指定 這個標記。

    將下列程式碼複製到 cc_toolchain_config.bzl

      # NEW
      load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
      # NEW
      load(
          "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
          "feature",
          "flag_group",
          "flag_set",
          "tool_path",
      )
    
      all_link_actions = [ # NEW
          ACTION_NAMES.cpp_link_executable,
          ACTION_NAMES.cpp_link_dynamic_library,
          ACTION_NAMES.cpp_link_nodeps_dynamic_library,
      ]
    
      def _impl(ctx):
          tool_paths = [
              tool_path(
                  name = "gcc",
                  path = "/usr/bin/clang",
              ),
              tool_path(
                  name = "ld",
                  path = "/usr/bin/ld",
              ),
              tool_path(
                  name = "ar",
                  path = "/bin/false",
              ),
              tool_path(
                  name = "cpp",
                  path = "/bin/false",
              ),
              tool_path(
                  name = "gcov",
                  path = "/bin/false",
              ),
              tool_path(
                  name = "nm",
                  path = "/bin/false",
              ),
              tool_path(
                  name = "objdump",
                  path = "/bin/false",
              ),
              tool_path(
                  name = "strip",
                  path = "/bin/false",
              ),
          ]
    
          features = [ # NEW
              feature(
                  name = "default_linker_flags",
                  enabled = True,
                  flag_sets = [
                      flag_set(
                          actions = all_link_actions,
                          flag_groups = ([
                              flag_group(
                                  flags = [
                                      "-lstdc++",
                                  ],
                              ),
                          ]),
                      ),
                  ],
              ),
          ]
    
          return cc_common.create_cc_toolchain_config_info(
              ctx = ctx,
              features = features, # NEW
              cxx_builtin_include_directories = [
                  "/usr/lib/llvm-9/lib/clang/9.0.1/include",
                  "/usr/include",
              ],
              toolchain_identifier = "local",
              host_system_name = "local",
              target_system_name = "local",
              target_cpu = "k8",
              target_libc = "unknown",
              compiler = "clang",
              abi_version = "unknown",
              abi_libc_version = "unknown",
              tool_paths = tool_paths,
          )
    
      cc_toolchain_config = rule(
          implementation = _impl,
          attrs = {},
          provides = [CcToolchainConfigInfo],
      )
    
  10. 如果執行 bazel build --config=clang_config //main:hello-world, 最終版本

檢查成果

在本教學課程中,您已瞭解如何設定基本的 C++ 工具鍊,但 工具鍊的功能比這個簡單的範例更加強大。

重點如下: - 您必須在指令列中指定 --crosstool_top 旗標, 指向cc_toolchain_suite - 您可以使用 .bazelrc 建立特定設定的捷徑 檔案 - cc_toolchain_suite 可能會針對不同的 CPU 和 CPU 列出 cc_toolchains 編碼器-解碼器架構您可以使用 --cpu 等指令列標記來區分。 - 您必須告知工具鍊的存在位置。本教學課程內容 有一個簡化的版本,可讓您從系統存取工具。如果 有興趣採用更獨立式的做法 工作區這裡。你的工具來自 而且就必須將這些檔案設為可供存取 已指向 cc_toolchain,且包含屬性上的目標依附元件,例如 compiler_files。您也必須變更 tool_paths。 - 您可以建立功能,自訂要傳遞到哪些標記 例如連結或任何其他動作類型

延伸閱讀

詳情請參閱 C++ 工具鍊設定