Created
April 27, 2017 09:27
-
-
Save olanod/fc302cfe884f20de9d35a76fe7ac0b1e to your computer and use it in GitHub Desktop.
Go makefile with cross compilation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
default: build | |
OS=$(shell uname | tr [:upper:] [:lower:]) | |
PLATFORMS=linux darwin freebsd | |
PKG_NAME=$(shell glide name) | |
APP_NAME=$(shell basename $(PKG_NAME)) | |
APP_VERSION=$(shell git describe --tags --always) | |
BRANCH?=$(shell git rev-parse --abbrev-ref HEAD) | |
BUILD_DIR?=build | |
BUILD_TYPE?=develop | |
ifeq ($(BUILD_TYPE),develop) | |
BUILD_FLAGS= | |
else | |
BUILD_FLAGS=-ldflags "-X main.version=$(APP_VERSION) -s -w" | |
endif | |
compile=GOOS=$(1) GOARCH=amd64 go build $(BUILD_FLAGS) -o $(2) $(3) | |
pack=tar -C $(1) -jcf $(2) $(3) | |
BIN_PATTERN=$(BUILD_DIR)/%/$(BRANCH)/$(APP_NAME) | |
PACK_FLAT_DIR=$(BUILD_DIR)/_pkg | |
# useful to produce packages organized in folders. E.g. S3 | |
PACK_FLAT_PATTERN=$(PACK_FLAT_DIR)/$(APP_NAME)-%-$(APP_VERSION).tar.bz2 | |
# useful to produce packages for flat displaying. E.g. Github releases | |
PACK_NEST_PATTERN=$(BIN_PATTERN).tar.bz2 | |
.PHONY: run build pack fpack clean | |
# Compile and run for current OS only | |
run: $(OS); $(<:%=$(BIN_PATTERN)) | |
# Compile for all platforms | |
build: $(PLATFORMS) | |
# Compile the specified platform. E.g. `make linux` | |
$(PLATFORMS): %: $(BIN_PATTERN) | |
$(BIN_PATTERN): cmd/server.go | |
$(call compile,$*,$@,$<) | |
# Package binaries for all platforms | |
pack: $(PLATFORMS:%=pack-%) | clean-bin | |
fpack: $(PLATFORMS:%=fpack-%) | clean-bin | |
# Create package for specified platform. E.g. `make pack-linux` | |
$(PLATFORMS:%=pack-%): pack-%: $(PACK_NEST_PATTERN) | |
# Optional way of creating packages in a flat hierarchy. E.g. `make fpack-linux` | |
$(PLATFORMS:%=fpack-%): fpack-%: $(PACK_FLAT_PATTERN) | |
$(PACK_FLAT_PATTERN): $(BIN_PATTERN) | |
@mkdir -p $(PACK_FLAT_DIR) | |
$(call pack,$(^D),$(PACK_FLAT_DIR)/$(@F),$(^F)) | |
$(PACK_NEST_PATTERN): $(BIN_PATTERN) | |
$(call pack,$(^D),$@,$(^F)) | |
clean: clean-bin clean-pack clean-fpack | |
clean-bin: | |
-rm -f $(PLATFORMS:%=$(BIN_PATTERN)) | |
clean-pack: | |
-rm -f $(PLATFORMS:%=$(PACK_NEST_PATTERN)) | |
clean-fpack: | |
-rm -rf $(PACK_FLAT_DIR) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Not an expert Makefile-maker but this works for my current go needs