Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@eleniums
Last active April 4, 2024 00:10
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save eleniums/06c30c50befcfe36e7840ca46c9ebacd to your computer and use it in GitHub Desktop.
Save eleniums/06c30c50befcfe36e7840ca46c9ebacd to your computer and use it in GitHub Desktop.
Sample Go Makefile to build binaries for Windows, Mac, and Linux.
EXECUTABLE=executable-name
WINDOWS=$(EXECUTABLE)_windows_amd64.exe
LINUX=$(EXECUTABLE)_linux_amd64
DARWIN=$(EXECUTABLE)_darwin_amd64
VERSION=$(shell git describe --tags --always --long --dirty)
.PHONY: all test clean
all: test build ## Build and run tests
test: ## Run unit tests
go test ./...
build: windows linux darwin ## Build binaries
@echo version: $(VERSION)
windows: $(WINDOWS) ## Build for Windows
linux: $(LINUX) ## Build for Linux
darwin: $(DARWIN) ## Build for Darwin (macOS)
$(WINDOWS):
env GOOS=windows GOARCH=amd64 go build -i -v -o $(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/service/main.go
$(LINUX):
env GOOS=linux GOARCH=amd64 go build -i -v -o $(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/service/main.go
$(DARWIN):
env GOOS=darwin GOARCH=amd64 go build -i -v -o $(DARWIN) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/service/main.go
clean: ## Remove previous build
rm -f $(WINDOWS) $(LINUX) $(DARWIN)
help: ## Display available commands
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
@ndabAP
Copy link

ndabAP commented Nov 1, 2022

Thanks a lot! My final version:

EXECUTABLE=
VERSION=$(shell git describe --tags --always --long --dirty)
WINDOWS=$(EXECUTABLE)_windows_amd64_$(VERSION).exe
LINUX=$(EXECUTABLE)_linux_amd64_$(VERSION)
DARWIN=$(EXECUTABLE)_darwin_amd64_$(VERSION)

.PHONY: all test clean

all: test build

test:
	go test ./...

build: windows linux darwin
	@echo version: $(VERSION)

windows: $(WINDOWS)

linux: $(LINUX)

darwin: $(DARWIN)

$(WINDOWS):
	env GOOS=windows GOARCH=amd64 go build -v -o bin/$(WINDOWS) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/service/main.go

$(LINUX):
	env GOOS=linux GOARCH=amd64 go build -v -o bin/$(LINUX) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/service/main.go

$(DARWIN):
	env GOOS=darwin GOARCH=amd64 go build -v -o bin/$(DARWIN) -ldflags="-s -w -X main.version=$(VERSION)" ./cmd/service/main.go

clean:
	rm -f $(WINDOWS) $(LINUX) $(DARWIN)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment