xref: /aosp_15_r20/external/bazelbuild-rules_go/docs/go/core/platform-specific_dependencies.md (revision 9bb1b549b6a84214c53be0924760be030e66b93a)
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
9When cross-compiling, you may have some platform-specific sources and
10dependencies. Source files from all platforms can be mixed freely in a single
11`srcs` list. Source files are filtered using [build constraints] (filename
12suffixes and `+build` tags) before being passed to the compiler.
13
14Platform-specific dependencies are another story. For example, if you are
15building a binary for Linux, and it has dependency that should only be built
16when targeting Windows, you will need to filter it out using Bazel [select]
17expressions:
18
19``` bzl
20go_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.
43The values are lists of labels. Exactly one of these
44lists will be selected, depending on the target configuration. rules_go has
45pre-declared `config_setting` rules for each OS, architecture, and
46OS-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
54