Skip to content

Makefile example in golang

homepage-banner

What is a Makefile?

A makefile is a file that contains a set of instructions for building and compiling a program or a set of programs. These instructions are written in a special language called make, which is designed to make it easy to manage complex software projects.

Makefile example for golang

Here is a simple example of a makefile for a golang project.

.DEFAULT_GOAL := build

BINARY="BinaryName"

fmt:
    go fmt ./
.PHONY: fmt

lint: fmt
    golint ./
.PHONY: lint

vet: fmt
    go vet ./
.PHONY: vet

build: vet
    go build hello.go
.PHONY:build

mac:
    CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build -o ${BINARY}

win:
    CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build -o ${BINARY}

run:
    @go run ./

gotool:
    go fmt ./
    go vet ./

clean:
    @if [ -f ${BINARY} ] ; then rm ${BINARY} ; fi

help:
    @echo "make - clean, format, build"
    @echo "make build - just build"
    @echo "make run - just run"
    @echo "make clean - clean binary file"
    @echo "make gotool - run fmt and vet tools"
    @echo "make mac - build for mac"
    @echo "make win - build for windows"

How Do Makefiles Work?

Makefiles work by using a set of rules to determine which files need to be compiled or updated. These rules are written in the make language and include information about the dependencies between different files in the project.

When you run the make command, it reads the makefile and checks the dependencies between the different files. If a file has been updated or is missing, make will automatically compile it and any files that depend on it. This makes it easy to manage large projects with lots of files and dependencies.

Benefits of Using Makefiles

There are several benefits to using makefiles in your projects. First, they can save you a lot of time by automating the build process. Instead of manually compiling each file, make will handle that for you automatically.

Second, makefiles make it easy to manage large projects with many files and dependencies. By defining the dependencies between different files in the project, make can automatically build any files that need to be updated.

Finally, makefiles are portable and can be used on many different platforms and operating systems. This makes it easy to share your projects with others and collaborate on them with other developers.

Conclusion

Makefiles are an essential tool for managing complex software projects. By automating the build process and managing dependencies between different files, makefiles can save you a lot of time and effort. If you’re not already using makefiles in your projects, it’s definitely worth taking the time to learn how to use them.

Leave a message