Using Makefile in golang
What is Makefile?
Makefiles are an incredibly useful automation tool that you can use to run and build not just your Go applications, but for most programming languages.
A Makefile is a simple text file used in software development to automate the process of building executable programs or other files from source code. It contains a set of directives and rules that specify how to compile and link source files, as well as other tasks such as cleaning up generated files.
To use this Makefile, you would typically place it in the same directory as your source files and then run make
in the terminal. The make
utility would then read the Makefile, determine the dependencies, and execute the necessary commands to build the program
target.
MakeFile in go
Now, let’s see these concepts in action with a really simple Makefile
example
1. Create go application
For this example we are creating a simple go application.
Add a simple Go application into the mix so that we can try our hand at defining new targets which will build and run this new Go app for us.
Create a main.go file. Add a simple application to print “Hello”.
package main
import "fmt"
func main() {
fmt.Println("Hello")
}
2. Create a Makefile
To create makefile, create a new file and name it Makefile
We have a simple Makefile
in a project directory that performs the task of printing out Hello
to our terminal.
Now let’s define some new targets within our Makefile
which will simplify the task of building and running our application for us.
Now open Makefile
and add following
hello:
echo "Hello"
build:
go build main.go
run:
go run main.go
When we run make build
in the terminal, Make reads the Makefile, identifies the build
target, and executes the associated command, which compiles main.go
into an executable named main
in the bin
directory.
Furthermore, when we run make hello
in the terminal, Make reads the Makefile, identifies the hello
target, and executes the associated command, which is it will print hello in the directory.
Layering Commands in Makefile
Let’s now imagine we are working with a complex system that has a multi-stage build/run process that has developed over many years. Instead of having to define all of the commands needed to build and run in a single target, you can break everything up into smaller targets and have something like an all
target combine them into one make
command.
Open up your Makefile
once again and add an all
as seen in example. This all
target will execute your hello
and build
targets in series.
hello:
echo "Hello"
build:
go build main.go
run:
go run main.go
all: hello build
Conclusion
Overall, Makefiles play a crucial role in Go development, simplifying the build process, managing dependencies, and enhancing productivity. By leveraging Makefiles, developers can streamline their workflow, reduce overhead, and focus on writing high-quality Go code.