Bazel go binary: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
=External=
* https://github.com/bazel-contrib/rules_go/blob/master/docs/go/core/rules.md#go_binary
=Internal=
=Internal=
* [[Bazel_BUILD_Files#go_binary|BUILD Files]]
* [[Bazel_BUILD_Files#go_binary|BUILD Files]]


=Overview=
=Overview=
<code>go_binary</code> builds a single <code>main</code> package and links it into an executable. It may embed the content of a <code>[[Bazel_go_library#Overview|go_library]]</code>, using the <code>embed</code> attribute. Embedded sources are compiled together in the same package. binaries can be built for alternative platforms and configurations by setting <code>goos</code>, <code>goarch</code> and other attributes.


=Example=
=Example=

Latest revision as of 06:58, 23 November 2024

External

Internal

Overview

go_binary builds a single main package and links it into an executable. It may embed the content of a go_library, using the embed attribute. Embedded sources are compiled together in the same package. binaries can be built for alternative platforms and configurations by setting goos, goarch and other attributes.

Example

load("//meta/rules:go.bzl", "go_binary", "go_library")

go_library(
    name = "lib",
    srcs = [
        "aux.go",
        "main.go",
    ],
    visibility = ["//visibility:private"],
)

go_binary(
    name = "somebin",
    embed = [":lib"],
    visibility = ["//visibility:public"],
)

To build the binary:

bazel build //somedir/someotherdir/some_bazel_package:somebin

To run the binary:

bazel run //somedir/someotherdir/some_bazel_package:somebin

To add dependencies, see:

BUILD Files Dependency Management

A More Complex Example

load("//meta/rules:go.bzl", "go_library", "go_binary")

go_library(
    name = "somepkg_lib",
    srcs = [
        "file1.go",
        "file2.go",
    ],
    importpath = "github.com/someorg/somemodule/pkg/somepkg",
    visibility = ["//visibility:private"],
    deps = [
        "//lib/a",
        "//lib/b",
        ...
        "@com_github_blang_semver//:semver",
    ],
)

go_binary(
    name = "somebin",
    embed = [":somepkg_lib"],
    visibility = ["//visibility:public"],
    x_defs = {"github.com/someorg/somemodule/version.Version": "{BUILD_VERSION}"},
)

To add dependencies, see:

BUILD Files Dependency Management