github.com/bazelbuild/rules_go@v0.47.2-0.20240515105122-e7ddb9ea474e/docs/go/core/platform-specific_dependencies.md (about)

     1    [build constraints]: https://golang.org/pkg/go/build/#hdr-Build_Constraints
     2    [select]: https://docs.bazel.build/versions/master/be/functions.html#select
     3    [config_setting]: https://docs.bazel.build/versions/master/be/general.html#config_setting
     4    [Gazelle]: https://github.com/bazelbuild/bazel-gazelle
     5  
     6  
     7  ## Platform-specific dependencies
     8  
     9  When cross-compiling, you may have some platform-specific sources and
    10  dependencies. Source files from all platforms can be mixed freely in a single
    11  `srcs` list. Source files are filtered using [build constraints] (filename
    12  suffixes and `+build` tags) before being passed to the compiler.
    13  
    14  Platform-specific dependencies are another story. For example, if you are
    15  building a binary for Linux, and it has dependency that should only be built
    16  when targeting Windows, you will need to filter it out using Bazel [select]
    17  expressions:
    18  
    19  ``` bzl
    20  go_binary(
    21      name = "cmd",
    22      srcs = [
    23          "foo_linux.go",
    24          "foo_windows.go",
    25      ],
    26      deps = [
    27          # platform agnostic dependencies
    28          "//bar",
    29      ] + select({
    30          # OS-specific dependencies
    31          "@io_bazel_rules_go//go/platform:linux": [
    32              "//baz_linux",
    33          ],
    34          "@io_bazel_rules_go//go/platform:windows": [
    35              "//quux_windows",
    36          ],
    37          "//conditions:default": [],
    38      }),
    39  )
    40  ```
    41  
    42  `select` accepts a dictionary argument. The keys are labels that reference [config_setting] rules.
    43  The values are lists of labels. Exactly one of these
    44  lists will be selected, depending on the target configuration. rules_go has
    45  pre-declared `config_setting` rules for each OS, architecture, and
    46  OS-architecture pair. For a full list, run this command:
    47  
    48  ``` bash
    49  $ bazel query 'kind(config_setting, @io_bazel_rules_go//go/platform:all)'
    50  ```
    51  
    52  [Gazelle] will generate dependencies in this format automatically.
    53