golang[103]-ldflags技巧

+X

1
2
3
4
5
6
7
8
package main

import "fmt"

var ServerBaseURL string
func main(){
fmt.Println(ServerBaseURL)
}

其中-w为去掉调试信息(无法使用gdb调试),-s为去掉符号表(暂未清楚具体作用)。
go build --ldflags “-s -w -X main.ServerBaseURL=http://localhost:8080 -X main.UseTor=” -o test main.go
./test:
output:

1
http://localhost:8080

打印日期

go build --ldflags “-s -w -X ‘main.ServerBaseURL=date’” -o test6 main.go

output:

1
Tue Dec  3 16:37:08 CST 2019

打印go语言版本

go build --ldflags “-s -w -X ‘main.ServerBaseURL=$(go version)’” -o test7 main.go
output:

1
go version go1.12.9 darwin/amd64

https://github.com/golang/go/wiki/GcToolchainTricks
https://ms2008.github.io/2018/10/08/golang-build-version/

可以使用 go tool link --help 查看 ldflags 各参数含义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
-B note
add an ELF NT_GNU_BUILD_ID note when using ELF
-D address
set data segment address (default -1)
-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
-a disassemble output
-buildid id
record id as Go toolchain build id
-buildmode mode
set build mode
-c dump call graph
-compressdwarf
compress DWARF if possible (default true)
-cpuprofile file
write cpu profile to file
-d disable dynamic executable
-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 dump symbol table
-o file
write output to file
-pluginpath string
full path name for plugin
-r path
set the ELF dynamic linker search path to dir1:dir2:...
-race
enable race detector
-s disable symbol table
-tmpdir directory
use directory for temporary files
-u reject unsafe packages
-v print link trace
-w disable DWARF generation

禁止gc优化和内联

1
go build -gcflags '-N -l'

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