Skip to content

Instantly share code, notes, and snippets.

@marz619

marz619/README.md

Last active Mar 26, 2020
Embed
What would you like to do?
Go build LDFlags

Using the -ldflags parameter can help set variable values at compile time.

Using the example provided here:

  1. Running make build will create a build executable. Running it will result in:
$> ./build
no version (Mon YYYY)
$>
  1. Running make build_version will use the version and date variables defined in the makefile and using the -ldflags option to set the values of version and date in main.go.
$> ./build
0.0.1 (Aug 2017)
$>

useful links

package main
var (
version string
date string
)
func init() {
if version == "" {
version = "no version"
}
if date == "" {
date = "(Mon YYYY)"
}
}
func main() {
println(version, date)
}
version=0.0.1
date=$(shell date -j "+(%b %Y)")
exec=a.out
.PHONY: all
all:
@echo " make <cmd>"
@echo ""
@echo "commands:"
@echo " build - runs go build"
@echo " build_version - runs go build with ldflags version=${version} & date=${date}"
@echo ""
build: clean
@go build -v -o ${exec}
build_version: check_version
@go build -v -ldflags '-X "main.version=${version}" -X "main.date=${date}"' -o ${exec}_${version}
clean:
@rm -f ${exec}
check_version:
@if [ -a "${exec}_${version}" ]; then \
echo "${exec}_${version} already exists"; \
exit 1; \
fi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment