Golang : Setting variable value with ldflags
This short tutorial will demonstrate how to initialize a variable value during runtime at the stage of compilation/linking. Go linker has an option to set the value of an uninitialised string variable:
-X symbol value
Set the value of an otherwise uninitialized string variable.
The symbol name should be of the form importpath.name,
as displayed in the symbol table printed by "go tool nm".
For example :
package main
import "fmt"
var str string
func main() {
fmt.Println(str)
}
and execute the program with -ldflags
to initialize the str variable value
$ go run -ldflags "-X main.str abc" main.go
or if you prefer, build it first into executable binary :
$ go build -ldflags "-X main.str 'abc'" main.go && ./main
Output :
abc
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.6k Golang : Gargish-English language translator
+9.1k Golang : Convert file content to Hex
+12.9k Golang : Check if a file exist or not
+7.8k Golang : Find duplicate files with filepath.Walk
+5.6k Golang : Spell checking with ispell example
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?
+20.6k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+11.3k Golang : How to display image file or expose CSS, JS files from localhost?
+18k Mac OSX : Homebrew and Golang
+5.1k Golang : Extract XML attribute data with attr field tag example
+5.1k Javascript : Get operating system and browser information
+44.5k Golang : Encode image to base64 example