Golang Build - A Complete Guide
Introduction
Golang comes with the go
command, used to build, test, and install Go packages and modules. The go
command is the primary tool for managing your Go source code. In this artilce we’ll explore the go build
command in detail.
What is go build
?
The go build
command compiles Go source code into a binary executable. The go build
also compiles the dependencies of that source code.
Examples
Let’s create a go programme called main.go
with the following content:
Remember to run go mod init
to create a go.mod
file. Then run go build
to compile the source code.
The -o
flag is used to specify the name of the output file. In this case, the output file is called awesome
. If you don’t specify the -o
flag, the output file will be called main
.
To run the output file, run ./awesome
in the terminal if you’re on Linux or Mac. If you’re on Windows, run awesome.exe
.
Build Flags
go build
comes with many flags that can be used to modify the build process. Here are some of the most commonly used build flags:
-a
- forces rebuilding of packages that are already up-to-date.-i
- installs the dependencies to$GOPATH/pkg
instead of the default temporary directory.-o
- specifies the name of the output file.-p
- specifies the number of programs, such as build commands or test binaries, that can be run in parallel.
-gcflags
The -gcflags
flag is used to pass arguments to the Go compiler. The -gcflags
flag is useful for debugging and performance tuning. For instace when exploring escape analysis, you can use the -gcflags
flag to show the escape analysis output.
Here is an example of a program that uses the -gcflags
flag to show the escape analysis output:
To show the escape analysis output, run the following command:
The -m=2
flag tells the compiler to show the escape analysis output. The -l
flag tells the compiler to disable inlining.
The output of the above command will be:
-ldflags
The -ldflags
flag is used to pass arguments to the linker.
Here is an example of a program that uses the -ldflags
flag to set the version of the program:
To set the version of the program, run the following command:
By default, the version of the program will be 1.0.0
. But, by using the -ldflags
flag, we can set the version of the program to 1.2.3
.
The output of the above command will be:
These are but a few examples of flags that we have used with the go build
command. For a full list of flags, run go help build
.
Conclusion
In this article we explored the go build
command in detail. We looked at some of thmmonly used build flags. We also looked at some examples of how to use the -gcflags
and -ldflags
flags.