Skip to content

Instantly share code, notes, and snippets.

@allex
Forked from marz619/README.md
Created March 11, 2019 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allex/4ba4a6a0afaf33e025e9931da6d3a0f0 to your computer and use it in GitHub Desktop.
Save allex/4ba4a6a0afaf33e025e9931da6d3a0f0 to your computer and use it in GitHub Desktop.
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