跳至主要內容

go build 常见编译优化 gcflags/ldflags

安格后端golanggolang大约 2 分钟...

一般情况下,go build 可以直接编译程序,无需额外的参数设定。
但在用于生产环境编译时 go build 的一些参数还是很有用的。

go build -gcflags '-N -l' \
  -ldflags '-w -s -X "main.appVersion=v1.0.0"' \
  -o myapp .

禁止 gc 优化和内联

go build -gcflags '-N -l'

说明:

  • -N 禁止编译优化
  • -l 禁止内联,禁止内联也可以一定程度上减小可执行程序大小
    可以使用 go tool compile --help 查看 gcflags 各参数含义

减小编译后可执行程序的大小

go build -ldflags '-w -s'

说明:

  • -w 禁止生成 debug 信息,注意使用该选项后,无法使用 gdb 进行调试
  • -s 禁用符号表
    可以使用 go tool link --help 查看 ldflags 各参数含义

定义 string 类型值

使用 go tool link --help 查看 ldflags 各参数含义, 可以看到 -X 选项的说明:

usage: link [options] main.o
  -B note
     add an ELF NT_GNU_BUILD_ID note when using ELF
  -E entry
     set entry symbol name
  -H type
     set header type
  -I linker
     use linker as ELF dynamic linker
  -L directory
     add specified directory to library path
  -R quantum
     set address rounding quantum (default -1)
  -T address
     set text segment address (default -1)
  -V print version and exit
  -X definition
     add string value definition of the form importpath.name=value
  ...
















 
 

通过指定 -ldflags 的参数 -X '{importpath}.{varName}={varValue}' 可以在编译时定义指定包中的 string 变量值, 比如: -X 'main.appVersion=v1.0.10' -X 'config.appName=demo 应用';

如果 value 值中包含空格的话可以把 {importpath}.{varName}={varValue} 这一段用单引号或双引号包起来,关于这点可以通过 go help build 中的这段看到:

The -asmflags, -gccgoflags, -gcflags, and -ldflags flags accept a space-separated list of arguments to pass to an underlying tool during the build. To embed spaces in an element in the list, surround it with either single or double quotes. The argument list may be preceded by a package pattern and an equal sign, which restricts the use of that argument list to the building of packages matching that pattern (see 'go help packages' for a description of package patterns).

通过例子来看下 -X 的作用效果吧

main.go
package main

import (
 "fmt"
)

var buildTime = ""
var goVersion = ""
var user = ""

func main() {
 fmt.Printf("BuildTime: %s\n", buildTime)
 fmt.Printf("GoVersion: %s\n", goVersion)
 fmt.Printf("授权给用户: %s\n", user)
}

执行 build.sh 可以看到如下输出结果

> sh ./build.sh
BuildTime: 2023-02-22 19:09:39
GoVersion: go version go1.20.1 darwin/amd64
授权给用户: 不看 小猪佩奇
 



转自:https://javasgl.github.io/go-build-args/open in new window go build 常见编译优化

上次编辑于:
你认为这篇文章怎么样?
  • 0
  • 0
  • 0
  • 0
  • 0
  • 0
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v3.1.3