How to use select to properly detect whether I am building C++ code in Windows or Linux?

@bazel_tools contains predefined platform conditions:

$ bazel query @bazel_tools//src/conditions:all
@bazel_tools//src/conditions:windows_msys
@bazel_tools//src/conditions:windows_msvc
@bazel_tools//src/conditions:windows
@bazel_tools//src/conditions:remote
@bazel_tools//src/conditions:host_windows_msys
@bazel_tools//src/conditions:host_windows_msvc
@bazel_tools//src/conditions:host_windows
@bazel_tools//src/conditions:freebsd
@bazel_tools//src/conditions:darwin_x86_64
@bazel_tools//src/conditions:darwin

You can use them directly in the BUILD file:

cc_library(
  name = "impl",
  srcs = ["Implementation.cpp"] + select({
    "@bazel_tools//src/conditions:windows": ["ImplementationWin.cpp"],
    "@bazel_tools//src/conditions:darwin": ["ImplementationMacOS.cpp"],
     "//conditions:default": ["ImplementationLinux.cpp"],
  }),
  # .. same for hdrs and data
)

cc_binary(
  name = "demo",
  deps = [":impl"],
)

See the documentation for select for details on the syntax.

Tags:

C++

Bazel