diff --git a/src/test/shell/bazel/cc_integration_test.sh b/src/test/shell/bazel/cc_integration_test.sh index 317313e77bbd53..908e183a4bf7f1 100755 --- a/src/test/shell/bazel/cc_integration_test.sh +++ b/src/test/shell/bazel/cc_integration_test.sh @@ -1708,4 +1708,51 @@ EOF expect_log "in pkg/library.cpp: ''" } +function test_compiler_flag_gcc() { + # The default macOS toolchain always uses XCode's clang. + [ "$PLATFORM" != "darwin" ] || return 0 + type -P gcc || return 0 + + cat > BUILD.bazel <<'EOF' +config_setting( + name = "gcc_compiler", + flag_values = {"@bazel_tools//tools/cpp:compiler": "gcc"}, +) + +cc_binary( + name = "main", + srcs = select({":gcc_compiler": ["main.cc"]}), +) +EOF + cat > main.cc <<'EOF' +int main() {} +EOF + + bazel build //:main --repo_env=CC=gcc || fail "Expected compiler flag to have value 'gcc'" +} + +function test_compiler_flag_clang() { + # TODO: The default toolchain always uses XCode's clang, but sets the compiler name to the generic + # "compiler". + [ "$PLATFORM" != "darwin" ] || return 0 + type -P clang || return 0 + + cat > BUILD.bazel <<'EOF' +config_setting( + name = "clang_compiler", + flag_values = {"@bazel_tools//tools/cpp:compiler": "clang"}, +) + +cc_binary( + name = "main", + srcs = select({":clang_compiler": ["main.cc"]}), +) +EOF + cat > main.cc <<'EOF' +int main() {} +EOF + + bazel build //:main --repo_env=CC=clang || fail "Expected compiler flag to have value 'clang'" +} + run_suite "cc_integration_test" diff --git a/tools/cpp/unix_cc_configure.bzl b/tools/cpp/unix_cc_configure.bzl index f6421f369cdebb..a5ca087144b505 100644 --- a/tools/cpp/unix_cc_configure.bzl +++ b/tools/cpp/unix_cc_configure.bzl @@ -279,6 +279,18 @@ def _coverage_flags(repository_ctx, darwin): def _is_clang(repository_ctx, cc): return "clang" in repository_ctx.execute([cc, "-v"]).stderr +def _is_gcc(repository_ctx, cc): + # GCC's version output uses the basename of argv[0] as the program name: + # https://gcc.gnu.org/git/?p=gcc.git;a=blob;f=gcc/gcc.cc;h=158461167951c1b9540322fb19be6a89d6da07fc;hb=HEAD#l8728 + return repository_ctx.execute([cc, "--version"]).stdout.startswith("gcc ") + +def _get_compiler_name(repository_ctx, cc): + if _is_clang(repository_ctx, cc): + return "clang" + if _is_gcc(repository_ctx, cc): + return "gcc" + return "compiler" + def _find_generic(repository_ctx, name, env_name, overriden_tools, warn = False, silent = False): """Find a generic C++ toolchain tool. Doesn't %-escape the result.""" @@ -492,7 +504,7 @@ def configure_unix_toolchain(repository_ctx, cpu_value, overriden_tools): "%{compiler}": escape_string(get_env_var( repository_ctx, "BAZEL_COMPILER", - "clang" if is_clang else "compiler", + _get_compiler_name(repository_ctx, cc), False, )), "%{abi_version}": escape_string(get_env_var(