go命令补遗 关于 golang build

可通过go help获取go命令,如下记录一些易忽略的go命令用法。

Go is a tool for managing Go source code.

Usage:

    go <command> [arguments]

The commands are:

    bug         start a bug report
    build       compile packages and dependencies
    clean       remove object files and cached files
    doc         show documentation for package or symbol
    env         print Go environment information
    fix         update packages to use new APIs
    fmt         gofmt (reformat) package sources
    generate    generate Go files by processing source
    get         add dependencies to current module and install them
    install     compile and install packages and dependencies
    list        list packages or modules
    mod         module maintenance
    run         compile and run Go program
    test        test packages
    tool        run specified go tool
    version     print Go version
    vet         report likely mistakes in packages

Use "go help <command>" for more information about a command.

Additional help topics:

    buildmode   build modes
    c           calling between Go and C
    cache       build and test caching
    environment environment variables
    filetype    file types
    go.mod      the go.mod file
    gopath      GOPATH environment variable
    gopath-get  legacy GOPATH go get
    goproxy     module proxy protocol
    importpath  import path syntax
    modules     modules, module versions, and more
    module-get  module-aware go get
    module-auth module authentication using go.sum
    module-private module configuration for non-public modules
    packages    package lists and patterns
    testflag    testing flags
    testfunc    testing functions

Use "go help <topic>" for more information about that topic.
go help

1. go build

缩小输出文件体积

go 编译出的文件,体积挺大的。一个重要原因是其中包含了调试信息,可以通过编译参数使其不包含调试信息。

# 移除 调试信息(-w) 和 符号表(-s)
go build -o main -ldflags "-w -s" main.go

上述操作使用 -ldflags 参数指定 -w 和 -s, 分别表示在编译时不包含调试信息和符号表,此举可以较好地缩减二进制文件体积。

编译时写入全局变量

go 可以通过编译参数,在编译时对变量进行赋值。一般情况下,这种操作可以让程序保留编译信息等数据。
通过 -ldflags 参数,设定 -X 操作,可以为全局变量赋值(一定要加-X)。

go build -ldflags "-X 'main.BuildTime=time006'" main.go
go build -ldflags "-X 'main.BuildTime=`date`' -X 'main.GitHash=`git rev-parse HEAD`'" main.go

go build -ldflags "-X cnca.HTTP2ClientTLSCAPath=/etc/openness/certs/ngc" -o "kubectl-cnca"

参考:

1. 关于 golang build

猜你喜欢

转载自www.cnblogs.com/embedded-linux/p/12820893.html
今日推荐