英文:
How to statically link a Go binary that uses crypto/tls?
问题
如果你尝试编译以下Go程序:
package main
import _ "crypto/tls"
func main() {
}
你将得到一个动态链接的Go二进制文件。这对我来说很烦人(我正在一个Docker容器中构建一个Go二进制文件,该容器使用与我的主机不同的libc,这将导致该二进制文件无法在我的主机上运行)。
如何强制Go静态构建这样的程序?
英文:
If you try to compile the following Go program:
package main
import _ "crypto/tls"
func main() {
}
You'll wind up with a dynamically linked Go binary. This is annoying for me (I'm building a Go binary inside a Docker container, which uses a different libc from my host, which will result in the binary not running on my host).
How does one force Go to build such a program statically?
答案1
得分: 9
crypto/tls
只在darwin操作系统中使用cgo,因为它需要调用FetchPEMRoots
函数来获取根证书机构。
你的程序使用cgo的原因是因为crypto/tls
导入了net
包,默认情况下net
包会链接到主机解析器。你可以使用"netgo"构建标签来在不使用cgo的情况下构建net
包。
go build -tags netgo
或者,如果你使用的是不会默认构建标准库包的版本,你可以使用新的installsuffix来触发它们的编译。
go build -installsuffix netgo -tags netgo
由于你的环境不需要也无法使用cgo,你可以使用CGO_ENABLED=0
来完全禁用cgo来构建所有内容。
英文:
The only OS where crypto/tls
uses cgo is darwin, where it needs to call FetchPEMRoots
to get the root CAs.
The reason your program is using cgo is because crypto/tls
imports the net
package, which links to the host resolver by default. You can build the net
package without cgo using the "netgo" build tag.
go build -tags netgo
Or if you're on a release where the std lib packages won't be built by default, you can trigger them to be compiled with a new installsuffix
go build -installsuffix netgo -tags netgo
Since you're not going to have the need or ability to use cgo in your environment, you may want to just build everything with CGO_ENABLED=0
to disable cgo entirely.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论