如何使用go build -ldflags在编译时设置布尔变量

时间:2014-12-03 11:52:08

标签: go ld

我有一个go程序test.go

package main

import "fmt"

var DEBUG_MODE bool = true    

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

我想在compile时间将DEBUG_MODE变量设置为false

我试过了:

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                                                                               

它不起作用,但在DEBUG_MODEstring

时有效

1 个答案:

答案 0 :(得分:5)

您只能使用-X链接器标志设置字符串变量。 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.

您可以改为使用字符串:

var DebugMode = "true"

然后

go build -ldflags "-X main.DebugMode=false" test.go && ./test