Go build
Internal
Overview
The go build
command compiles one or more packages. If a "main" package is among the arguments, the tool creates an executable as described below. The following flags apply:
TO DEPLETE: Go_Commands_-_build
Build an Executable with go build
go build [options] <main-package-import-path>
Note that depending on whether the package is part of module or not, the main package import path may include the module path.
The executable is placed in the directory go build
is executed from.
The name of the executable is given by the last segment of the main package import path, and it can be configured with the -o
command line option. The argument of -o
can be the new name of the executable file, in which case the executable will be written in the current directory, or an absolute or relative path, in which case the executable, named after the last segment of the path, will be written at the given path.
Package within a Module
An a/b/c
main package with a similar layout, but this time included within an example.com
module
. ├─ a │ └─ b │ └─ c │ └─ main.go # package main └─ go.mod
can have its executable built with:
go build [-o blue] example.com/a/b/c
The exact directory within the project go build
is run from it does not matter, the tool will locate go.mod
and will use relative paths to that. The only aspect influenced by where the compilation tool runs is where it will place the final executable.
Executable Name
If no -o
flag is used, the name of the executable will be given by the name of the directory that contains the Go file that belongs to the main
package. This behavior can be overridden with -o
.
Package without Module Support
In case of a package without module support, with the go
tool configured in GOPATH mode (GOPATH
configured to include the parent of the src
directory and GO111MODULE
set to "auto"), and with this directory layout:
. └─ src └─ a └─ b └─ c └─ main.go # package main
the executable is built with:
go build a/b/c
The executable will be named "c", based on the last segment of the package import path and will be place in the directory go build
was executed from. To change the name of the executable, use the -o
option:
go build -o blue a/b/c
This will create an executable named "blue".
Options
-C
Change to the specified directory before running the command. This is the final executable result will be placed.
-ldflags
Arguments to pass to each go tool link invocation. Useful to provide the value of variables during the linking time. Works for both go build
and go test
.
go build -ldflags '[pattern=]linker_arg_list' [...]
or:
go build -ldflags='linker_arg_list' [...]
Example:
go build -ldflags="-X 'example.com/myapp/internal/version.Version=1.2.0'" [...]
The value can be generated dynamically during linking with:
go build -ldflags="-X 'example.com/myapp/internal/version.Version='$(some-command arg1 arg2)" [...]
For more details on the linker options, see:
-tags
See: