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
+4.7k Unix/Linux : How to open tar.gz file ?
+7.8k Golang : automatically figure out array length(size) with three dots
+30k Golang : Math pow(the power of x^y) example
+5.9k Golang : Fibonacci number generator examples
+42.4k Golang : Use wildcard patterns with filepath.Glob() example
+4.7k Linux : Disable and enable IPv4 forwarding
+5.9k Golang : Mapping Iban to Dunging alphabets
+7.7k Golang : GMail API create and send draft with simple upload attachment example
+5.5k Golang : When to use make or new?
+12k Golang : Calculate elapsed years or months since a date
+10.3k Golang : Byte format example
+13.2k Golang : How to shuffle elements in array or slice?