Published on

Makefile for automating Go workflow

Authors
  • avatar
    Name
    Galuh Pradipta
    Twitter

How to Write a Makefile to Automate Go Workflow

If you are developing a Go project and want to automate your workflow, a Makefile can help you streamline your tasks. A Makefile is a simple text file that contains a set of rules describing how to build your project. In this tutorial, we will go over how to write a Makefile to automate your Go workflow.

Step 1: Install Go

Before we start writing our Makefile, we need to install Go on our machine. Visit the official Go website and download the latest version of Go for your operating system. Once installed, check that Go is properly installed by running the following command in your terminal:

$ go version

Step 2: Create a New Go Project

Next, let's create a new Go project. Create a new directory for your project and navigate to it in your terminal:

$ mkdir myproject
$ cd myproject

Now, create a new Go file named main.go:

$ touch main.go

Step 3: Write Your Go Code

Open main.go in your favorite editor and write some code. For example:

package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

Step 4: Write Your Makefile

Now that we have our Go code ready, let's write a Makefile to automate our workflow. Create a new file named Makefile in your project directory and open it in your editor.

Here's a basic Makefile that will compile and run our Go code:

.PHONY: build run clean

build:
    GOOS=linux GOARCH=amd64 go build -o myproject main.go
    GOOS=windows GOARCH=amd64 go build -o myproject.exe main.go

run:
    ./myproject

clean:
    rm myproject myproject.exe

Let's break down what each rule does:

  • build: Compiles our Go code and creates an executable named myproject for both Linux and Windows operating systems.
  • run: Runs the myproject executable.
  • clean: Deletes the myproject and myproject.exe executables.

Step 5: Test Your Makefile

To test your Makefile, go to your terminal and navigate to your project directory. Then, run the following command:

$ make build

This will compile your Go code and create executables named myproject and myproject.exe. Next, run the following command to execute your program:

$ make run

You should see the output Hello, World! in your terminal.

Finally, to clean up your project directory, run the following command:

$ make clean

Conclusion

In this tutorial, we learned how to write a Makefile to automate our Go workflow. By using a Makefile, we can easily compile, run, and clean our project without having to remember complex commands. Makefiles are a great way to simplify your workflow and make your code more organized. Happy coding!