deepwzh的技术笔记
  • Golang
  • Python
  • Cpp
杂项
前端开发
  • 计算机网络
  • 操作系统
  • 数据库
云原生
Devops
AIGC
关于作者
  • Golang
  • Python
  • Cpp
杂项
前端开发
  • 计算机网络
  • 操作系统
  • 数据库
云原生
Devops
AIGC
关于作者
  • Golang
  • 工具
  • 最佳实践
  • 学习资料
  • 代码生成
  • 安装与配置

    • 安装与配置
    • GVM
    • 私有仓库拉取
    • 安装与配置
  • 库

    • 库
    • Grpc-go
    • 命令行参数
    • 依赖注入库 wire
  • 编译器

    • 编译器
    • clean
    • 逃逸分析
    • 编译过程
    • 构建选项
    • 编译优化

      • 编译优化
      • PGO
  • 语言

    • 语言
    • defer
    • go:embed
  • 微服务框架

    • 微服务框架
    • Kratos

      • Kratos
      • 集成三方 web 框架
      • 项目结构体系

构建选项

调试相关

-x

打印构建的详细命令

go build -x .

—work

构建后不要删除临时构建目录(可以配合-x 使用)

go build -x --work .

输出示例:

WORK=/tmp/go-build1130336169
cd /home/deepwzh/demo
git status --porcelain
cd /home/deepwzh/demo
git -c log.showsignature=false show -s --format=%H:%ct
packagefile flag=/home/deepwzh/.cache/go-build/a0/a0b491429288e113192cf2d6f24dd2bb5e99f02311c9428412af3103b6260d91-d
packagefile github.com/gin-gonic/gin=/home/deepwzh/.cache/go-build/bd/bdbc84e1f3e7833a2ca403de507607a237b5c5f7a32b11894daed4d3ca9ab458-d
packagefile log=/home/deepwzh/.cache/go-build/5c/5c9b0eebe18c7a993c8a9f96fa7253f3b2bbc4655cb4368f18d2f72f4b2f6f2e-d
...(省略若干packagefile)
modinfo "xxxxx"
EOF
mkdir -p $WORK/b001/exe/
cd .
/usr/local/go/pkg/tool/linux_amd64/link -o 
$WORK/b001/exe/a.out -importcfg $
WORK/b001/importcfg.link -buildmode=exe -buildid=zwNLzxoOVcB9QVRnw7yV/xXJYi_x8M4dZIf1lIuL2/NaglquxDuAStj9xsdue2/zwNLzxoOVcB9QVRnw7yV -extld=gcc $WORK/b001/
_pkg_
.a
/usr/local/go/pkg/tool/linux_amd64/buildid -w $WORK/b001/exe/a.out # internal
mv $WORK/b001/exe/a.out xxxxx

-n

打印编译期间用到的命令,而不是执行他们

检测相关

-race

竞态检测

gcflags(编译标记)

gcflags 在每次 go tool compile 调用时传递参数。

常用参数

  • -N -l: 禁用所有优化
  • -N: 禁用优化
  • -l: 禁用内联
  • mypackage1=-N mypackage2=-l : 不同包指定不同的参数
  • -S : 打印汇编代码
  • -r : 打印包的依赖关系
  • -m : 打印内存分配信息
  • -B: 禁用边界检查

完整参数

使用 go tool compile --help 可以查看完整的参数帮助

usage: compile [options] file.go...
  -%    debug non-static initializers
  -+    compiling runtime
  -B    disable bounds checking
  -C    disable printing of columns in error messages
  -D path
        set relative path for local imports
  -E    debug symbol export
  -I directory
        add directory to import search path
  -K    debug missing line numbers
  -L    also show actual source file names in error messages for positions affected by //line directives
  -N    disable optimizations
  -S    print assembly listing
  -V    print version and exit
  -W    debug parse tree after type checking
  -asan
        build code compatible with C/C++ address sanitizer
  -asmhdr file
        write assembly header to file
  -bench file
        append benchmark times to file
  -blockprofile file
        write block profile to file
  -buildid id
        record id as the build id in the export metadata
  -c int
        concurrency during compilation (1 means no concurrency) (default 8)
  -clobberdead
        clobber dead stack slots (for debugging)
  -clobberdeadreg
        clobber dead registers (for debugging)
  -complete
        compiling complete package (no C or assembly)
  -coveragecfg file
        read coverage configuration from file
  -cpuprofile file
        write cpu profile to file
  -d value
        enable debugging settings; try -d help
  -dwarf
        generate DWARF symbols (default true)
  -dwarfbasentries
        use base address selection entries in DWARF (default true)
  -dwarflocationlists
        add location lists to DWARF in optimized mode (default true)
  -dynlink
        support references to Go symbols defined in other shared libraries
  -e    no limit on number of errors reported
  -embedcfg file
        read go:embed configuration from file
  -env definition
        add definition of the form key=value to environment
  -errorurl
        print explanatory URL with error message if applicable
  -gendwarfinl int
        generate DWARF inline info records (default 2)
  -goversion string
        required version of the runtime
  -h    halt on error
  -importcfg file
        read import configuration from file
  -installsuffix suffix
        set pkg directory suffix
  -j    debug runtime-initialized variables
  -json string
        version,file for JSON compiler/optimizer detail output
  -l    disable inlining
  -lang string
        Go language version source code expects
  -linkobj file
        write linker-specific object to file
  -linkshared
        generate code that will be linked against Go shared libraries
  -live
        debug liveness analysis
  -m    print optimization decisions
  -memprofile file
        write memory profile to file
  -memprofilerate rate
        set runtime.MemProfileRate to rate
  -msan
        build code compatible with C/C++ memory sanitizer
  -mutexprofile file
        write mutex profile to file
  -nolocalimports
        reject local (relative) imports
  -o file
        write output to file
  -p path
        set expected package import path
  -pack
        write to file.a instead of file.o
  -pgoprofile file
        read profile or pre-process profile from file
  -r    debug generated wrappers
  -race
        enable race detector
  -shared
        generate code that can be linked into a shared library
  -smallframes
        reduce the size limit for stack allocated objects
  -spectre list
        enable spectre mitigations in list (all, index, ret)
  -std
        compiling standard library
  -symabis file
        read symbol ABIs from file
  -t    enable tracing for debugging the compiler
  -traceprofile file
        write an execution trace to file
  -trimpath prefix
        remove prefix from recorded source file paths
  -v    increase debug verbosity
  -w    debug type checking
  -wb
        enable write barrier (default true)

ldflags(链接标记)

ldflags 用于在每次 go tool link 调用时传递参数。以下是一些常用的 ldflags 参数:

常用参数

  • -s : 省略符号表和调试信息
  • -w : 省略 DWARF 调试信息
  • -X : 设置字符串变量的值

完整参数

使用 go tool link --help 可以查看完整的参数帮助

usage: link [options] main.o
  -B note
        add an ELF NT_GNU_BUILD_ID note when using ELF; use "gobuildid" to generate it from the Go build ID
  -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 int
        set the start address of text symbols (default -1)
  -V    print version and exit
  -X definition
        add string value definition of the form importpath.name=value
  -a    no-op (deprecated)
  -asan
        enable ASan interface
  -aslr
        enable ASLR for buildmode=c-shared on windows (default true)
  -benchmark string
        set to 'mem' or 'cpu' to enable phase benchmarking
  -benchmarkprofile base
        emit phase profiles to base_phase.{cpu,mem}prof
  -bindnow
        mark a dynamically linked ELF object for immediate function binding
  -buildid id
        record id as Go toolchain build id
  -buildmode mode
        set build mode
  -c    dump call graph
  -capturehostobjs string
        capture host object files loaded during internal linking to specified dir
  -checklinkname
        check linkname symbol references (default true)
  -compressdwarf
        compress DWARF if possible (default true)
  -cpuprofile file
        write cpu profile to file
  -d    disable dynamic executable
  -debugnosplit
        dump nosplit call graph
  -debugtextsize int
        debug text section max size
  -debugtramp int
        debug trampolines
  -dumpdep
        dump symbol dependency graph
  -extar string
        archive program for buildmode=c-archive
  -extld linker
        use linker when linking in external mode
  -extldflags flags
        pass flags to external linker
  -f    ignore version mismatch
  -g    disable go package data checks
  -h    halt on error
  -importcfg file
        read import configuration from file
  -installsuffix suffix
        set package directory suffix
  -k symbol
        set field tracking symbol
  -libgcc string
        compiler support lib for internal linking; use "none" to disable
  -linkmode mode
        set link mode
  -linkshared
        link against installed Go shared libraries
  -memprofile file
        write memory profile to file
  -memprofilerate rate
        set runtime.MemProfileRate to rate
  -msan
        enable MSan interface
  -n    no-op (deprecated)
  -o file
        write output to file
  -pluginpath string
        full path name for plugin
  -pruneweakmap
        prune weak mapinit refs (default true)
  -r path
        set the ELF dynamic linker search path to dir1:dir2:...
  -race
        enable race detector
  -randlayout int
        randomize function layout
  -s    disable symbol table
  -strictdups int
        sanity check duplicate symbol contents during object file reading (1=warn 2=err).
  -tmpdir directory
        use directory for temporary files
  -v    print link trace
  -w    disable DWARF generation

PGO

Go 的 PGO(Profile-Guided Optimization, profile-guided optimization)技术是一种通过运行时性能分析数据来指导编译器优化的技术。它通过收集程序在实际运行中的性能数据(如函数调用频率、热点代码等),再利用这些数据优化编译过程,从而提升程序的执行效率。

Golang 编译的时候可以选择使用 pgo 进行优化,可以使用选项指定 PGO 的配置文件路径,当传入 off 会关闭 PGO 选项,默认选项为 auto。

当指定特殊名称 “auto” 时,对于构建中的每个主包,go 命令会在该包的目录中查找一个名为 “default.pgo” 的文件(如果该文件存在),并将其应用于主包的(传递性)依赖项(其他包不受影响)。

specify the file path of a profile for profile-guided optimization (PGO).
            When the special name "auto" is specified, for each main package in the
            build, the go command selects a file named "default.pgo" in the package's
            directory if that file exists, and applies it to the (transitive)
            dependencies of the main package (other packages are not affected).
            Special name "off" turns off PGO. The default is "auto".

toolchain

-toolexec 'cmd args'
            a program to use to invoke toolchain programs like vet and asm.
            For example, instead of running asm, the go command will run
            'cmd args /path/to/asm <arguments for asm>'.
            The TOOLEXEC_IMPORTPATH environment variable will be set,
            matching 'go list -f {{.ImportPath}}' for the package being built.

其他选项

选项
用法
备注
-a
强制重新编译所有依赖包
一般不需要使用,而是按需清除编译缓存(详见go clean)
-installsuffix

自Go 1.10以后,你不必再使用`installsuffix`参数(或许更早的版本)
-tags
支持类似c的条件编译

-buildmode
构建模式,除了默认可执行文件外,还支持静态链接库,动态链接库

参考资料

https://colobu.com/2018/08/13/create-minimal-docker-image-for-go-applications/

Prev
编译过程