Home > Enterprise >  using ldflags for giving binary file a version not working in golang
using ldflags for giving binary file a version not working in golang

Time:03-30

The main.go as follows:

package main

func main() {
    println("hello world")
}

The Makefile as follows:

flags=-X main.version=1.5.0

build:
    go build -ldflags "$(flags)" -o main main.go

Then I run make, and got main file.

After I runing ./main -v, I just got:

hello world

Why it does not display 1.5.0?

go version is go version go1.18 darwin/arm64, when I run go version -m main, I got:

main: go1.18
        path    command-line-arguments
        build   -compiler=gc
        build   -ldflags="-X main.version=1.5.0"
        build   CGO_ENABLED=1
        build   CGO_CFLAGS=
        build   CGO_CPPFLAGS=
        build   CGO_CXXFLAGS=
        build   CGO_LDFLAGS=
        build   GOARCH=arm64
        build   GOOS=darwin

I had a misunderstanding of ldflags. It works as follows:

package main

import (
    "fmt"
    "os"
)

var (
    version string
)

func main() {
    args := os.Args
    if len(args) == 2 && (args[1] == "--version" || args[1] == "-v") {
        fmt.Printf("project version: %s \n", version)
        return
    }
}
$ ./main -v 
project version: 1.5.0

CodePudding user response:

The variable you're setting with ldflags (version) must be declared in the package at the package level. The handling of -v you yourself must implement.

package main

import "flag"

var version string

func main() {
    var vFlag bool
    flag.BoolVar(&vFlag, "v", false, "show version")
    flag.Parse()
    
    if vFlag {
        println(version)
    } else {
        println("hello world")
    }
}
go build -ldflags "-X main.version=1.5.0" -o main main.go
./main -v
# 1.5.0
./main
# hello world
  •  Tags:  
  • go
  • Related