user3856970
user3856970

Reputation: 339

In Bazel, how to prevent some C++ compiler flags from passing to external dependencies?

Our project is written in C++ and uses gRPC as a dependency. We are using clang as compiler. We set up the C++ toolchain file with -Wall -Werror, but this is causing issues with the warnings raised by gRPC itself.

Is there a way to prevent Bazel from applying the Werror flag to the gRPC files, but still apply it elsewhere in the project?

The files look like this:

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", ...]
....


UPDATE 9/2/2020 Based on Ondrej's very help solution, I've solved this issue in the following way.

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"]

Then, at the top of each of the BUILD files in my own project, add this line:

package(features = ["compile_flags_with_werror"])

This has the effect of applying -Werror when compiling files in my project, but not when compiling any external dependencies.

Upvotes: 5

Views: 3062

Answers (1)

Ondrej K.
Ondrej K.

Reputation: 9664

You can define toolchain feature such as:

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

Which is enabled by default and add it to features of create_cc_toolchain_config_info() to add the desired flags (removing them from your default_compile_flags_feature).

Then for the misbehaving external dependencies, you can disable the feature for an entire package in its BUILD file:

package(features = ["-warning_flags"])

Or do so on per target basis:

cc_library(
    name = "external_lib",
    ...
    features = ["-warning_flags"],
)

Upvotes: 1

Related Questions