go-build
Compile Go source code into executables
TLDR
Compile a 'package main' file (output will be the filename without extension)
Compile, specifying the output filename
Compile a package
Compile a main package into an executable, enabling data race detection
SYNOPSIS
go build [build flags] [packages]
PARAMETERS
-o output
Specify the output file name. This overrides the default name based on the package path or source file name. When compiling a single source file, the output will be named output.
-i
Install the packages that are dependencies of the target.
-gcflags flags
Pass flags to the Go compiler.
-ldflags flags
Pass flags to the linker.
-race
Enable data race detection. This adds extra instrumentation to the code to detect race conditions at runtime.
-msan
Enable memory sanitizer. This adds instrumentation to the code to detect memory-related errors at runtime.
-n
Print the commands that would be executed but do not execute them. (dry run mode).
-x
Print the commands.
packages
Specifies the packages to build. Can be a list of package import paths, file names, or patterns.
DESCRIPTION
The go build
command compiles Go source code into executable binaries or library packages.
It's a fundamental tool in the Go toolchain for creating runnable programs and reusable components.
The command automatically manages dependencies, fetching and building any required packages.
It optimizes the build process, supporting cross-compilation to target different operating systems and architectures.
By default, go build
compiles packages in the current directory and places the output executable in the same directory.
You can specify package paths to build specific packages or modules.
It supports building shared libraries and plugins. Flags enable control over the build process, including optimization levels, debugging information, and target platform.
CAVEATS
Building C or C++ dependencies might require appropriate compilers and build tools installed on your system.
Cross-compilation may require setting environment variables like GOOS
and GOARCH
.
BUILD MODES
go build
supports different build modes using the -buildmode
flag. Examples: default
(executable), archive
(package archive), plugin
, shared
ENVIRONMENT VARIABLES
Environment variables such as GOOS
(operating system), GOARCH
(architecture), and CGO_ENABLED
affect the build process.
HISTORY
The go build
command has been a core part of the Go programming language since its initial release in 2009.
It's evolved over time to include features like module support (with go mod
), improved dependency management, and better support for cross-compilation.
Its primary goal is to provide a simple and efficient way to compile Go code and manage dependencies.