使用标准库是否可以构建Go二进制文件?

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

Is it possible to build a Go binary using the standard library?

问题

经过研究源代码,我认为这是不可能的,但是可以使用类似以下方式构建一个Go二进制文件:

import "package/from/stdlib"

func main() {
    ...
    stdlib.BuildBinary(path)
    ...
}

链接:

(我正在尝试简化CI流水线中的构建阶段)

英文:

Having studied the source code I don't think it's possible, but can a Go binary be built using something like:

import "package/from/stdlib"

func main() {
	...
	stdlib.BuildBinary(path)
	...
}

https://github.com/golang/go/blob/master/src/cmd/go/main.go
https://github.com/golang/go/blob/master/src/cmd/go/internal/work/build.go

(I'm trying to simplify a build stage in a CI pipeline)

答案1

得分: 2

不,标准库不包含编译器的源代码。编译器的源代码可以在这里找到:https://github.com/golang/go/tree/release-branch.go1.20/src/cmd/compile

但是,如果你安装了标准库,那应该是Go安装的一部分,其中包含了Go工具,可以提供交叉编译支持。所以简而言之,你只需要(官方的)Go安装包。如果你想将源代码编译成可执行二进制文件,可以调用go工具作为外部命令。

需要注意的是,尽管标准库不包含编译器和链接器的代码,但你可以使用标准库来解析Go源代码。可以参考go/astgo/parser包。

英文:

No, the standard lib does not contain the compiler's (source) code. The compiler's source is available here: https://github.com/golang/go/tree/release-branch.go1.20/src/cmd/compile

But if you have the standard lib, that should be part of a Go installation, which contains the Go tool, giving you cross-compilation support. So in short: all you need is the (official) Go installation. Call the go tool as an external command if you want to compile source code into an executable binary.

Note however that even though the standard lib does not contain the compiler and linker's code, you can use the standard lib to parse Go sources. See the go/ast and go/parser packages.

huangapple
  • 本文由 发表于 2023年7月26日 17:08:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76769616.html
匿名

发表评论

匿名网友

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

确定