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
+23.6k Golang : Call function from another package
+6.3k Golang : Join lines with certain suffix symbol example
+19.6k Golang : Compare floating-point numbers
+26.9k Golang : dial tcp: too many colons in address
+13k Android Studio : Password input and reveal password example
+8.8k Golang : Gonum standard normal random numbers example
+6.6k Golang : Normalize email to prevent multiple signups example
+5.3k PHP : Convert string to timestamp or datestamp before storing to database(MariaDB/MySQL)
+8.2k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+25.4k Golang : missing Mercurial command
+10.6k Golang : Fix go.exe is not compatible with the version of Windows you're running
+6.9k Golang : Of hash table and hash map