如何静态链接使用crypto/tls的Go二进制文件?

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

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 FetchPEMRootsto 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.

huangapple
  • 本文由 发表于 2016年1月17日 23:12:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/34839897.html
匿名

发表评论

匿名网友

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

确定