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.3k Python : Convert(cast) string to bytes example
+8.2k Golang : Tell color name with OpenCV example
+7k Golang : Levenshtein distance example
+88k Golang : How to convert character to ASCII and back
+7.4k Golang : Calculate how many weeks left to go in a given year
+15.8k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+16k Golang : Read large file with bufio.Scanner cause token too long error
+14.1k Golang : Compress and decompress file with compress/flate example
+29.2k Golang : missing Git command
+10k Golang : Turn string or text file into slice example
+11.7k Golang : Convert(cast) float to int
+17.7k Golang : Upload/Receive file progress indicator