使用go build -ldflags设置编译时的布尔变量的方法是什么?

huangapple go评论77阅读模式
英文:

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

问题

我有一个名为test.go的Go程序。

package main

import "fmt"

var DEBUG_MODE bool = true

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

我想在编译时将DEBUG_MODE变量设置为false

我尝试过:

go build -ldflags "-X main.DEBUG_MODE 0" test.go && ./test
true

go build -ldflags "-X main.DEBUG_MODE false" test.go && ./test
true

go build -ldflags "-X main.DEBUG_MODE 0x000000000000" test.go && ./test
true

这并不起作用,但当DEBUG_MODE是一个string时可以工作。

英文:

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

答案1

得分: 6

你只能使用-X链接器标志来设置字符串变量。来自文档

-X importpath.name=value
将importpath中名为name的字符串变量的值设置为value。
注意,在Go 1.5之前,此选项需要两个单独的参数。
现在它接受一个在第一个等号上分割的参数。

你可以使用字符串代替:

var DebugMode = "true"

然后执行:

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

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

huangapple
  • 本文由 发表于 2014年12月3日 19:52:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/27271094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定