/ Greyhat.dk /

Kim Gert Nielsen

Go's gopher

Setting variables in a package on build time

Setting variables in a package on build time

When building a go binary its possible to add ldflags in order to variables in build time (Like version numbers) and this is pretty well documented. But setting variables in internal/vendoring directories it not well documented.

This is how its done

test # tree
├── cmd
│   └── cli
│       └── main.go
├── internal
│   └── cmd
│       └── version.go


package main

import "fmt"
import "test/internal/cmd"

func main() {

    fmt.Printf("Version: %s\n", cmd.Getversion())


package cmd

var version = "Not set"

func Getversion() string {
    return version

This has to be done with full path like

# go build -ldflags "-X test/internal/cmd.version=1.0.0-0529a3e" -o test ./cmd/cli/*.go
# ./test
Version: 1.0.0-0529a3e