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

本教學課程使用範例情境說明如何為專案設定 C++ 工具鍊。它是根據 C++ 專案範例為基礎,該專案使用 clang 不會發生錯誤。

課程內容

在本教學課程中,您會瞭解如何:

  • 設定建構環境
  • 設定 C++ 工具鍊
  • 建立為 cc_toolchain 提供額外設定的 Starlark 規則,以便 Bazel 使用 clang 建構應用程式
  • 在 Linux 機器上執行 bazel build --config=clang_config //main:hello-world,確認預期結果
  • 建構 C++ 應用程式

事前準備

設定建構環境

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

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

  1. 如果您尚未下載並安裝 Bazel 0.23,請立即下載。

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

  3. main/BUILD 檔案中加入下列 cc_binary 目標:

    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++ 工具鍊

如要設定 C++ 工具鍊,請重複建構應用程式,並依照以下說明逐一移除每個錯誤。

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

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

    由於您在 .bazelrc 檔案中指定了 --crosstool_top=//toolchain:clang_suite,因此 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_suite.toolchains 屬性中的每個值定義 cc_toolchain 目標。請將以下內容新增到 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
    

    接著,在 toolchain/BUILD 檔案中加入 ":k8_toolchain_config" 目標:

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

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

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

    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 中的 tools_path() 建構函式:

    # 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 需要知道要搜尋包含的標頭的位置。有很多方法可以解決這個問題 (例如使用 cc_binaryincludes 屬性),但在工具鍊層級透過 cc_common.create_cc_toolchain_config_infocxx_builtin_include_directories 參數解決這個問題。請注意,如果您使用其他版本的 clang,則包含路徑會有所不同。這些路徑也可能因分佈情形而異。

    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 和編譯器的 cc_toolchains。您可以使用指令列旗標 (例如 --cpu) 加以區分。- 您必須讓工具鍊知道工具的所在位置。本教學課程提供簡化版本,方便您從系統存取工具。如想使用更獨立的方法,請參閱這裡的工作區相關說明。工具可能來自不同的工作區,而您必須根據屬性 (例如 compiler_files) 將其檔案提供給 cc_toolchain 使用。您也必須變更 tool_paths。- 您可以建立功能,自訂要傳遞至不同動作的標記,標記或其他動作類型都一樣。

其他資訊

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