Bazel: How do you centralize all "config_setting" into a single BUILD (or bzl) file?

Viewed 25

I'd like to use a common set of config_settings for select across about 40 different BUILD files. I've figured out how to use a bzl file to provide common functionality to those BUILD files; however, I cannot seem to put config_setting into the bzl file, and cannot figure out how to specify them globally.

For example

load("@rules_cc//cc:defs.bzl", _cc_library = "cc_library")

# This does not work
config_setting(
    name = "clang_build",
    values = { "@bazel_tools//tools/cpp:compiler": "clang" },
)

config_setting(
    name = "gcc_build",
    values = { "@bazel_tools//tools/cpp:compiler": "gcc" },
)

_CLANG_OPTS = ["..."]
_GCC_OPTS = ["..."]

def internal_cc_library(
        name,
        copts = [],
        deps = [],
        defines = [],
        **kargs):
    _cc_library(
        name = name,
        copts = select({
           ":clang_buid": _CLANG_OPTS,
           ":gcc_buid": _GCC_OPTS,
           # etc...
        }) + copts,
        deps = deps,
        include_prefix = cple_include_prefix(native.package_name()),
        **kargs
        )

# ---- In the BUILD file

load("//bazel:internal_builds.bzl", "internal_cc_library")

internal_cc_library(name = "example", srcs = "hello_world.cc")

So, where can I specify my dozen or so config_setting flags, so that internal_cc_library will work as expected in every BUILD file where it is used?

1 Answers

config_setting is a rule, so it needs to be in a BUILD file. You can put it in a macro that the BUILD file calls, but ultimately it needs to be in the BUILD file, not the top level of a .bzl file.

Once you do that, use absolute labels to refer to them. Something like @//bazel:gcc_build (if you put them in that BUILD file you mentioned).

Related