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

回報問題 查看來源 夜間 7.2 7.1 7.0 6.5 6.4

本教學課程會使用範例情境來說明如何設定 C++ 工具鍊

課程內容

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

  • 設定建構環境
  • 使用 --toolchain_resolution_debug 對工具鍊解析度進行偵錯
  • 設定 C++ 工具鍊
  • 建立 Starlark 規則, cc_toolchain 的設定,讓 Bazel 能建構應用程式 合作頻道:clang
  • 透過執行下列指令來建構 C++ 二進位檔 Linux 電腦上的 bazel build //main:hello-world
  • 執行 bazel build //main:hello-world --platforms=//:android_x86_64,為 Android 跨平台編譯二進位檔

事前準備

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

設定建構環境

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

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

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

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

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

    因為 Bazel 在建構期間會使用許多以 C++ 編寫的內部工具, 如 process-wrapper,就會指定 主機平台如此一來,這些內部工具就能以 建立 Kubernetes 叢集所需的工具鍊因此,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
    

    Bazel 會在不指定 --platforms 的情況下,建構目標 @local_config_platform//:host正在使用 @bazel_tools//cc_configure_extension/local_config_cc//:cc-compiler-k8

設定 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++ 工具鍊。如要修正這項錯誤,請建立 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 規則,請新增載入量 陳述式 新增至 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

    # 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 必須知道要在哪裡搜尋已納入的標頭。另有 解決這個問題,例如使用 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-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 才能 會解析為平台上相同限制值的工具鍊。 請參閱這篇文章,進一步瞭解語言特定設定旗標的相關資訊。
  • 您必須告知工具鍊的存在位置。本教學課程內容 有一個簡化的版本,可讓您從系統存取工具。如果 有興趣採用更獨立式的做法 工作區你的工具來自 而且就必須將這些檔案設為可供存取 已指向 cc_toolchain,且包含屬性上的目標依附元件,例如 compiler_files。您也必須變更 tool_paths
  • 您可以建立功能,自訂要傳遞至哪些旗標 例如連結或任何其他動作類型

延伸閱讀

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