Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set boolean variable on compile time using go build -ldflags

Tags:

go

ld

I have a go program test.go

package main

import "fmt"

var DEBUG_MODE bool = true    

func main() {
  fmt.Println(DEBUG_MODE)
}

I want to set the DEBUG_MODE variable on the compile time to false

I've tried:

go build -ldflags "-X main.DEBUG_MODE 0" test.go && ./test 
true                                                                                                                                                                                                                             
kyz@s497:18:49:32:/tmp$ go build -ldflags "-X main.DEBUG_MODE false" test.go && ./test 
true                                                                                                                                                                                                                             
kyz@s497:18:49:41:/tmp$ go build -ldflags "-X main.DEBUG_MODE 0x000000000000" test.go && ./test                                                                                                                                  
true                                                                               

It doesn't work, but it works when DEBUG_MODE is a string

like image 831
Kokizzu Avatar asked Dec 03 '14 11:12

Kokizzu


1 Answers

You can only set string variables with -X linker flag. From the docs:

-X importpath.name=value
    Set the value of the string variable in importpath named name to value.
    Note that before Go 1.5 this option took two separate arguments.
    Now it takes one argument split on the first = sign.

You can use a string instead:

var DebugMode = "true"

and then

go build -ldflags "-X main.DebugMode=false" test.go && ./test
like image 85
Ainar-G Avatar answered Nov 09 '22 15:11

Ainar-G