在 Bazel 中,如何防止某些 C++ 编译器标志传递给外部依赖项?

use*_*970 5 c++ bazel bazel-rules

我们的项目是用 C++ 编写的,并使用 gRPC 作为依赖项。我们使用 clang 作为编译器。我们使用 来设置 C++ 工具链文件-Wall -Werror,但这会导致 gRPC 本身引发的警告出现问题。

有没有办法阻止 Bazel 将Werror标志应用于 gRPC 文件,但仍将其应用于项目中的其他地方?

这些文件看起来像这样:

WORKSPACE:
git_repository(
  name = "com_github_grpc_grpc",
  remote = "https://github.com/grpc/grpc",
  ...
)
load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
grpc_deps()
load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps")
grpc_extra_deps()
...


BUILD:
cc_binary(
  name = "one_of_many_binaries",
  srcs = ["source_1.cc"],
  deps = ["@com_github_grpc_grpc//:grpc++", 
         ...],
)
...


cc_toolchain_config.bzl:
default_compile_flags_feature = feature(
        name = "default_compile_flags",
        enabled = True,
        flag_sets = [
            flag_set(
                actions = all_compile_actions,
                flag_groups = [
                    flag_group(
                        flags = ["-Wall", "-Werror", ...]
....


Run Code Online (Sandbox Code Playgroud)

更新 9/2/2020 基于 Ondrej 非常有帮助的解决方案,我通过以下方式解决了这个问题。

  • 从我拥有该标志的功能中删除该-Werror标志(以及其他标志)并放入一个新功能中,该功能默认情况下处于禁用状态,如下所示:
compile_flags_with_werror = feature(
        name = "compile_flags_with_werror",
        enabled = False, #this is important
        flag_sets = [
            flag_set(
                actions = all_compile_actions,
                flag_groups = [
                    flag_group(
                        flags = ["-Werror"]
Run Code Online (Sandbox Code Playgroud)

然后,在我自己的项目中每个 BUILD 文件的顶部添加以下行:

package(features = ["compile_flags_with_werror"])

这在编译我的项目中的文件时具有应用效果-Werror,但在编译任何外部依赖项时不具有应用效果。

Ond*_* K. 1

您可以定义工具链功能,例如:

warning_flags_feature = feature(
    name = "warning_flags",
    enabled = True,
    flag_sets = [
        flag_set(
            actions = all_compile_actions,
            flag_groups = [
                flag_group(
                    flags = [
                        "-Wall",
                        "-Werror",
                    ],
                ),
            ],
        ),
    ],
)        
Run Code Online (Sandbox Code Playgroud)

默认情况enabled下,将其添加到featuresofcreate_cc_toolchain_config_info()以添加所需的标志(从您的 中删除它们default_compile_flags_feature)。

然后,对于行为不当的外部依赖项,您可以在其文件中禁用整个包的该功能BUILD

package(features = ["-warning_flags"])
Run Code Online (Sandbox Code Playgroud)

或者根据每个目标执行此操作:

cc_library(
    name = "external_lib",
    ...
    features = ["-warning_flags"],
)
Run Code Online (Sandbox Code Playgroud)