如何使用gccgo构建完整的Go程序二进制文件?

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

How to build full go program binary with gccgo?

问题

我注意到使用go build时,二进制结果可能超过2MB;但是使用gccgo时,二进制文件小于35k。

我还注意到使用gccgo时的另一个问题是,生成的二进制文件在另一个Linux系统上无法运行(我认为是缺少libgo.so),但是go build生成的二进制文件可以正常运行(所以我想这可能是因为二进制文件包含了运行所需的所有内容);有没有办法在gccgo中实现这一点?

英文:

I have noticed that when using go build the binary result can be in excess of 2MB; but using gccgo the binary is less than 35k.

The other issue that I noticed when using gccgo is that the produced binary isn't runnable on another linux box (missing libgo.so I believe) but the go build binary runs just fine (so I imagine its because the binary includes all that is necessary to run?); is there a way to do this with gccgo?

答案1

得分: 8

你必须使用-static标志:

> 使用-static选项进行完全静态链接(gc编译器的默认选项)。

http://golang.org/doc/install/gccgo

英文:

You have to use the -static flag:

> Use the -static option to do a fully static link (the default for the gc compiler).

http://golang.org/doc/install/gccgo

答案2

得分: 5

你可以使用-static-libgo选项,将libgo静态链接,同时动态链接系统库。(仅适用于gccgo)。

英文:

You can link libgo statically, while still linking the system libraries dynamically, by using the -static-libgo option. (This applies to gccgo only).

答案3

得分: 0

使用go 1.8或更高版本,如果使用CGO_ENABLED=1(默认为1)构建go,则进行本地编译动态链接。通过运行go env CGO_ENABLED来检查此变量。
在运行go build时,您可以通过将环境变量CGO_ENABLED设置为0来切换到静态链接。

CGO_ENABLED=0 go build

顺便说一句,交叉编译会自动使用静态链接。

英文:

With go 1.8 or above, if go is built with CGO_ENABLED=1 (default to 1), a native compilation links dynamically. Check this variable by running go env CGO_ENABLED.
You can switch to link statically by set the environment variable CGO_ENABLED to 0 when running go build.

CGO_ENABLED=0 go build

BTW, cross compiling uses static linkage automatically.

huangapple
  • 本文由 发表于 2013年3月26日 22:49:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/15640054.html
匿名

发表评论

匿名网友

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

确定