Go Programming: Basic Makefile

Rambabu Yerajana
2 min readApr 5, 2023

--

Here’s a basic Makefile you can use to compile your main.go file:

# Makefile for compiling main.go

# Compiler settings
GO = go
GOFLAGS = -v

# Targets
TARGET = main

# Build rules
.PHONY: all clean

all: $(TARGET)

$(TARGET): *.go
$(GO) build $(GOFLAGS) -o $@ $^

clean:
rm -f $(TARGET)

This Makefile uses $(GO) build to compile all the Go source files (*.go) in the directory into the $(TARGET) executable file.

Let’s break it down:

  • The # symbol at the beginning of a line indicates a comment.
  • The GO variable is set to the name of the Go compiler (go).
  • The GOFLAGS variable is set to the compiler flags we want to use when building the executable.
  • The TARGET variable is set to the name of the executable we want to create (main).
  • The .PHONY target tells Make that all and clean are not real files, but just phony targets that don't need to be built.
  • The all target is the default target that will be built when you run make. It depends on the $(TARGET) target.
  • The $(TARGET) target depends on all the Go source files (*.go) and will be built by compiling them together using the Go compiler.
  • The $^ variable expands to all the dependencies of the target (*.go in this case).
  • The clean target removes the executable file.

Here’s a more detailed explanation of how the $(TARGET) target works:

$(TARGET): *.go
$(GO) build $(GOFLAGS) -o $@ $^

This rule says that the $(TARGET) target depends on all the Go source files (*.go), and that it should be built by running the $(GO) build command with the specified flags. Here's what each part of the command does:

  • $(GO) expands to the name of the Go compiler (go).
  • build is the name of the Go command that compiles and links Go source code to create an executable.
  • $(GOFLAGS) expands to the compiler flags we want to use (-v in this case, which tells the compiler to be verbose).
  • -o $@ specifies the name of the output file ($@ expands to the name of the target, which is $(TARGET) or main in this case).
  • $^ expands to all the dependencies of the target (*.go in this case), which tells the compiler to compile all the Go source files into the executable.

I hope this explanation helps!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response