给定一个可执行文件,我能否确定用于构建它的GOOS和GOARCH的值?

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

Given an executable can I determine values of GOOS and GOARCH used to build it?

问题

根据go可执行文件,你可以如何确定GOOS和GOARCH的值?

英文:

The title pretty much sums it up. How can I determine what the values of GOOS and GOARCH was given just the go executable?

答案1

得分: 10

**编辑:**在Go 1.10中,runtime.GOROOT()的行为发生了变化,详细信息请参见Go 1.10发布说明#Runtime。基本上,现在runtime.GOROOT()会检查GOROOT环境变量是否设置,如果设置了,则返回其值。如果没有设置,则返回编译时记录的GOROOT值。


请查看runtime包:

> GOARCH、GOOS、GOPATH和GOROOT环境变量完整地构成了Go环境变量集。它们影响Go程序的构建(参见https://golang.org/cmd/go和https://golang.org/pkg/go/build)。GOARCH、GOOS和GOROOT在编译时记录,并通过此包中的常量或函数提供,但它们不影响运行时系统的执行。

可以在这里找到GOARCHGOOS的可能组合列表:https://golang.org/doc/install/source#environment

所以你要找的是runtime包中的常量:

runtime.GOOS
runtime.GOARCH

它们将准确地包含在构建应用程序时存在的值。

例如,看看这个简单的应用程序:

func main() {
	fmt.Println(runtime.GOOS)
	fmt.Println(runtime.GOARCH)
}

假设GOOS=windowsGOARCH=amd64。使用go run xx.go运行它将打印:

windows
amd64

从中构建一个exe文件(例如go build)。运行该exe文件将产生相同的输出。

现在将GOARCH更改为386。如果使用go run运行它(或构建一个exe文件并运行它),它将打印:

windows
386

如果运行先前构建的exe文件,它仍然会打印:

windows
amd64
英文:

EDIT: The behavior of runtime.GOROOT() changed in Go 1.10, for details, see Go 1.10 release notes # Runtime. Basically now runtime.GOROOT() checks if the GOROOT environment variable is set, and if so, its value is returned. If not, it returns the GOROOT value recorded at compile time.


Check out the runtime package:

> The GOARCH, GOOS, GOPATH, and GOROOT environment variables complete the set of Go environment variables. They influence the building of Go programs (see https://golang.org/cmd/go and https://golang.org/pkg/go/build). GOARCH, GOOS, and GOROOT are recorded at compile time and made available by constants or functions in this package, but they do not influence the execution of the run-time system.

A list of possible combinations for GOARCH and GOOS can be found here: https://golang.org/doc/install/source#environment

So what you are looking for are constants in the runtime package:

runtime.GOOS
runtime.GOARCH

And they will exactly contain the values that were present when your app was built.

For example see this simple app:

func main() {
	fmt.Println(runtime.GOOS)
	fmt.Println(runtime.GOARCH)
}

Let's say GOOS=windows and GOARCH=amd64. Running it with go run xx.go will print:

windows
amd64

Build an exe from it (e.g. go build). Running the exe has the same output.

Now change GOARCH to 386. If you run it with go run (or build an exe and run that), it will print:

windows
386

If you run the previously built exe, it will still print:

windows
amd64

huangapple
  • 本文由 发表于 2016年2月27日 20:22:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/35669727.html
匿名

发表评论

匿名网友

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

确定