0

I would like to specify linkopts on a cc_library target, but only if the target is built with clang (because gcc doesn't support the flag). How do I go about this?

The specific example in which this need arose is https://pigweed-review.googlesource.com/c/pigweed/pigweed/+/136287 (see also comments on this change). A library produces a warning when linked with clang with the --warn_backrefs flag. This warning can be silenced using --warn-backrefs-exclude, but only clang recognizes this flag: adding it unconditionally will lead gcc to report an error.

Apparently, CMake allows handling such compiler-specific flags via CMAKE_CXX_COMPILER_ID and CMAKE_<LANG>_COMPILER_VERSION. Is there an analogous mechanism in Bazel?

1 Answer 1

0

You can use a Bazel config. Create in the root directory of your workspace (where WORKSPACE or WORKSPACE.bazel is located) a file name .bazelrc. You can now define different configs, e.g. gcc11, clang14 or vs2022:

# GCC 11
build:gcc11 --cxxopt=-std=c++20
build:gcc11 --cxxopt=-Wall
build:gcc11 --cxxopt=-Werror
build:gcc11 --cxxopt=-Wno-volatile
build:gcc11 --cxxopt=-Wextra


# Clang 14
build:clang14 --cxxopt=-std=c++20
build:clang14 --cxxopt=--warn-backrefs-exclude

# Visual Studio 2022
build:vs2022 --cxxopt=/std:c++20
build:vs2022 --cxxopt=/Zc:__cplusplus
build:vs2022 --enable_runfiles # https://github.com/bazelbuild/bazel/issues/8843
build:vs2022 --copt=-DWIN32_LEAN_AND_MEAN
build:vs2022 --copt=-DNOGDI
build:vs2022 --host_copt=-DWIN32_LEAN_AND_MEAN
build:vs2022 --host_copt=-DNOGDI
build:vs2022 --define compiler=vs2022

Now when you call Bazel you can handover a preferred config, e.g.:

bazel build --config=clang14 //...

Another way could be to make use of platforms.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.