# How to set package variable using -ldflags -X in Golang build – go如何在编译时用ldflags设置变量

## Including build information in the executable

The gc toolchain linker, cmd/link, provides a -X option that may be used to record arbitrary information in a Go string variable at link time. The format is -X importpath.name=val. Here importpath is the name used in an import statement for the package (or main for the main package), name is the name of the string variable defined in the package, and val is the string you want to set that variable to. When using the go tool, use its -ldflags option to pass the -X option to the linker.

Let’s suppose this file is part of the package company/buildinfo:

You can build the program using this package using go build -ldflags="-X 'company/buildinfo.BuildTime=$(date)'" to record the build time in the string. (The use of$(date) assumes you are using a Unix-style shell.)

The string variable must exist, it must be a variable, not a constant, and its value must not be initialized by a function call. There is no warning for using the wrong name in the -X option. You can often find the name to use by running go tool nm on the program, but that will fail if the package name has any non-ASCII characters, or a " or % character.

## golang在编译、测试、安装时使用-ldflags -X动态设置包中变量的值

go install/build/test 时可以通过命令行参数设置 package的变量， 其格式为-X importpath.name=val, 其中importpath是变量所在包的的路径， name是包中定义的变量， val 是需要在编译时设置的变量的值(string)， 注意name表示的变量只能是变量(variable)，不能是常量(constant), 且不能通过函数调用的方式初始化，其类型只能是string， 不可是int, bool等.

Example: