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

回報問題 查看原始碼

本教學課程會使用範例情境,說明如何為專案設定 C++ 工具鍊。

課程內容

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

  • 設定建構環境
  • 使用 --toolchain_resolution_debug 對工具鍊解析進行偵錯
  • 設定 C++ 工具鍊
  • 建立為 cc_toolchain 提供額外設定的 Starlark 規則,讓 Bazel 能使用 clang 建構應用程式
  • 在 Linux 電腦上執行 bazel build //main:hello-world,建構 C++ 二進位檔
  • 執行 bazel build //main:hello-world --platforms=//:android_x86_64 來交叉編譯 Android 二進位檔

事前準備

本教學課程假設您位於 Linux,且已成功建構 C++ 應用程式,並安裝適當的工具和程式庫。本教學課程使用 clang version 16,您可以在系統上安裝這個憑證。

設定建構環境

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

  1. 如果您尚未下載並安裝 Bazel 7.0.2 以上版本,請先完成這項操作。

  2. 在根資料夾新增空白的 WORKSPACE 檔案。

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

    load("@rules_cc//cc:defs.bzl", "cc_binary")
    
    cc_binary(
        name = "hello-world",
        srcs = ["hello-world.cc"],
    )
    

    由於 Bazel 在建構期間會使用以 C++ 編寫的許多內部工具 (例如 process-wrapper),因此會為主機平台指定現有的預設 C++ 工具鍊。這樣就能使用這些內部工具,透過本教學課程中建立的工具鍊進行建構。因此,cc_binary 目標也使用預設工具鍊建構。

  4. 使用下列指令執行建構作業:

    bazel build //main:hello-world
    

    如未在 WORKSPACE 中註冊任何工具鍊,建構成功。

    如要進一步查看背後的運作原理,請執行以下指令:

    bazel build //main:hello-world --toolchain_resolution_debug='@bazel_tools//tools/cpp:toolchain_type'
    
    INFO: ToolchainResolution: Target platform @@local_config_platform//:host: Selected execution platform @@local_config_platform//:host, type @@bazel_tools//tools/cpp:toolchain_type -> toolchain @@bazel_tools~cc_configure_extension~local_config_cc//:cc-compiler-k8
    

    如未指定 --platforms,Bazel 會使用 @bazel_tools//cc_configure_extension/local_config_cc//:cc-compiler-k8@local_config_platform//:host 建構目標

設定 C++ 工具鍊

如要設定 C++ 工具鍊,請按照下方所述,重複建構應用程式並逐一刪除各項錯誤。

並假設 clang version 9.0.1,不過詳細資料只能在不同版本的 Clang 之間稍有變化。

  1. 透過以下方式新增toolchain/BUILD

    filegroup(name = "empty")
    
    cc_toolchain(
        name = "linux_x86_64_toolchain",
        toolchain_identifier = "linux_x86_64-toolchain",
        toolchain_config = ":linux_x86_64_toolchain_config",
        all_files = ":empty",
        compiler_files = ":empty",
        dwp_files = ":empty",
        linker_files = ":empty",
        objcopy_files = ":empty",
        strip_files = ":empty",
        supports_param_files = 0,
    )
    
    toolchain(
        name = "cc_toolchain_for_linux_x86_64",
        toolchain = ":linux_x86_64_toolchain",
        toolchain_type = "@bazel_tools//tools/cpp:toolchain_type",
        exec_compatible_with = [
            "@platforms//cpu:x86_64",
            "@platforms//os:linux",
        ],
        target_compatible_with = [
            "@platforms//cpu:x86_64",
            "@platforms//os:linux",
        ],
    )
    

    接著,使用 WORKSPACE 註冊工具鍊

    register_toolchains(
        "//toolchain:cc_toolchain_for_linux_x86_64"
    )
    

    這個步驟會定義 cc_toolchain,並繫結至主機設定的 toolchain 目標。

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

    ERROR: toolchain/BUILD:4:13: in toolchain_config attribute of cc_toolchain rule //toolchain:linux_x86_64_toolchain: rule '//toolchain:linux_x86_64_toolchain_config' does not exist.
    
  3. toolchain/BUILD 檔案中,定義空白檔案群組,如下所示:

    package(default_visibility = ["//visibility:public"])
    
    filegroup(name = "linux_x86_64_toolchain_config")
    
  4. 再次執行建構作業。Bazel 會擲回以下錯誤:

    '//toolchain:linux_x86_64_toolchain_config' does not have mandatory providers: 'CcToolchainConfigInfo'.
    

    CcToolchainConfigInfo 是您用來設定 C++ 工具鍊的提供者。如要修正這項錯誤,請建立含有以下內容的 toolchain/cc_toolchain_config.bzl 檔案,建立可為 Bazel 提供 CcToolchainConfigInfo 的 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 規則,請將載入陳述式新增至套件陳述式下方的 toolchain/BUILD

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

    然後將「linux_x86_64_toolchain_config」檔案群組替換為 cc_toolchain_config 規則宣告:

    cc_toolchain_config(name = "linux_x86_64_toolchain_config")
    
  5. 再次執行建構作業。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 中的 tool_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 是系統的正確路徑。

  6. 再次執行建構作業。Bazel 會擲回以下錯誤:

    ERROR: main/BUILD:3:10: Compiling main/hello-world.cc failed: absolute path inclusion(s) found in rule '//main:hello-world':
    the source file 'main/hello-world.cc' includes the following non-builtin files with absolute paths (if these are builtin files, make sure these paths are in your toolchain):
      '/usr/include/c++/13/ctime'
      '/usr/include/x86_64-linux-gnu/c++/13/bits/c++config.h'
      '/usr/include/x86_64-linux-gnu/c++/13/bits/os_defines.h'
      ...
    

    Bazel 必須知道要在何處搜尋包含的標頭。有很多方法可以解決這個問題,例如使用 cc_binaryincludes 屬性,但以下的做法是以 cc_common.create_cc_toolchain_config_infocxx_builtin_include_directories 參數在工具鍊層級解決。請注意,如果您使用其他版本的 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-16/lib/clang/16/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,
    )
    
  7. 再次執行建構指令,系統會顯示如下所示的錯誤:

    /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 屬性。解決這個問題的方法是確保使用工具鍊的任何目標都不必指定此標記。

    將下列程式碼複製到 toolchain/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",    # NEW
        "flag_group", # NEW
        "flag_set",   # NEW
        "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],
    )
    
  8. 執行 bazel build //main:hello-world 後,最終應能成功建構主機的二進位檔。

  9. toolchain/BUILD 中複製 cc_toolchain_configcc_toolchaintoolchain 目標,然後在目標名稱中將 linux_x86_64 取代為 android_x86_64

    WORKSPACE 中註冊 Android 工具鍊

    register_toolchains(
        "//toolchain:cc_toolchain_for_linux_x86_64",
        "//toolchain:cc_toolchain_for_android_x86_64"
    )
    
  10. 執行 bazel build //main:hello-world --android_platforms=//toolchain:android_x86_64 以建構 Android 二進位檔。

實際上,Linux 和 Android 應有不同的 C++ 工具鍊設定。您可以針對差異修改現有的 cc_toolchain_config,或是為個別平台建立個別規則 (例如 CcToolchainConfigInfo 提供者)。

檢查作業

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

重點整理如下:

  • 您必須在指令列中指定相符的 platforms 標記,讓 Bazel 能解析為平台上相同的限制值工具鍊。這份說明文件提供更多語言專屬設定旗標的相關資訊
  • 您必須讓工具鍊知道這些工具的位置。本教學課程提供簡化的版本,可讓您從系統存取工具。如果您想瞭解更獨立的方法,請參閱工作區一文。您的工具可能來自不同的工作區,而您必須針對屬性 (如 compiler_files) 的目標依附元件,提供檔案供 cc_toolchain 使用。也需要變更 tool_paths
  • 您可以建立功能,指定要將哪些標記傳遞至不同動作,例如連結或任何其他類型的動作。

其他資訊

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