在使用go build时,如何在链接标志的值字符串中包含空格?

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

How to contain space in value string of link flag when using go build

问题

以下是测试代码m.go的中文翻译:

package main

var version string

func main() {
    println("ver =", version)
}

如果我使用go 1.5进行编译和链接:

go tool compile m.go
go tool link -o m -X main.version="abc 123" m.o

可以正常工作。

但是如果我使用go 1.5的build命令:

go build -o m -ldflags '-X main.version="abc 123"' m.go

它会显示帮助信息,这意味着出现了一些问题。

如果我将语法更改为1.4:

go build -o m -ldflags '-X main.version "abc 123"' m.go

它可以正常工作,只是会有一个警告信息:

link: warning: option -X main.version abc 123 may not work in future releases; use -X main.version=abc 123

如果参数值中没有空格,可以正常工作:

go build -o m -ldflags '-X main.version=abc123' m.go

因为编译和链接正常工作,所以我认为这不是链接部分的问题。
我比较了go1.4和go 1.5的构建源代码,对于ldflags部分,看起来没有什么变化。当然,我可以使用一些特殊字符来替换空格,然后在程序中将其改回来,但为什么要这样做呢?我是否遗漏了什么?使用-ldflags的正确语法是什么?谢谢。

英文:

Here is test code m.go:

package main

var version string

func main() {
    println("ver = ", version)
}

If I compile and link with go 1.5:

go tool compile m.go
go tool link -o m -X main.version="abc 123" m.o

Works fine.

But if I use build command with go 1.5:

go build -o m -ldflags '-X main.version="abc 123"' m.go

It will show help message, which means something wrong

If I change to 1.4 syntax:

go build -o m -ldflags '-X main.version "abc 123"' m.go

It works except a warning message:

link: warning: option -X main.version abc 123 may not work in future releases; use -X main.version=abc 123

If it has no space in parameter value, works fine:

go build -o m -ldflags '-X main.version=abc123' m.go

Because compile and link works fine, So I think it is not link part issue.
I compared go1.4 and go 1.5 source code of build, for ldflags part, looks nothing changed. Of cause I can use some spacial char to replace space then in program to change it back, but why? Is there something I missed? What is the right syntax to use -ldflags ? Thanks

答案1

得分: 15

文档中可以看到:

注意,在Go 1.5之前,此选项需要两个单独的参数。
现在它只需要一个参数,以第一个等号分隔。

将整个参数用引号括起来:

go build -o m -ldflags '-X "main.version=abc 123"' m.go
英文:

From the documentation:

> Note that before Go 1.5 this option took two separate arguments.
> Now it takes one argument split on the first = sign.

Enclose the entire argument in quotes:

go build -o m -ldflags '-X "main.version=abc 123"' m.go

huangapple
  • 本文由 发表于 2015年9月9日 06:30:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/32468283.html
匿名

发表评论

匿名网友

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

确定