如何使用 select 正确检测我是在 Windows 还是 Linux 中构建 C++ 代码?

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

我正在编写一个示例 C++ 项目,该项目使用 Bazel 作为其他协作者可以遵循的示例习语。

这里是存储库:https://github.com/thinlizzy/bazelexample

我很想知道我是否正在这样做 'right',更具体地说是关于这个文件:https://github.com/thinlizzy/bazelexample/blob/38cc07931e58ff5a888dd6a83456970f76d7e5b3/demo/BUILD 在选择特定实现时。

cc_library(
    name = "demo",
    srcs = ["demo.cpp"],
    deps = [
        "//example:frontend",
    ],
)

cc_binary(
    name = "main_win",
    deps = [
        ":demo",
        "//example:impl_win",
    ],
)

cc_binary(
    name = "main_linux",
    deps = [
        ":demo",
        "//example:impl_linux",
    ],
)

这是否遵循 Bazel 项目的 correct/expected 习惯用法?我已经为其他项目这样做了,通过将所有特定于平台的依赖项集中在单独的目标中,然后二进制文件只依赖于它们。

bazel-discuss 列表中有人告诉我改用 select,但我尝试 'detect' 操作系统失败。我确定我做错了什么,但缺乏信息和示例并不能告诉我如何正确使用它。

@bazel_tools 包含预定义的平台条件:

$ 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

您可以直接在 BUILD 文件中使用它们:

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

有关语法的详细信息,请参阅 select 的文档。

向您的项目添加 .bazelrc。添加行 build:vs2019 --cxxopt=/std:c++14build:gcc --cxxopt=-std=c++14。构建您的代码 bazel build --config=msvc //...bazel build --config=gcc //....

@Vertexwahn 的回答让我有些困惑,所以我希望这个回答有助于澄清一点。虽然他的回答与问题没有直接关系,但它可能对其他试图在完全不同的平台上构建而不包含特定文件的人有用。

这是我回答那个特定问题的 link:How do I specify portable build configurations for different operating systems for Bazel?