Go的编译可执行文件的大小的原因 [英] Reason for huge size of compiled executable of Go

查看:118
本文介绍了Go的编译可执行文件的大小的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个hello world Go程序,它在我的linux机器上生成了本地可执行文件。但我很惊讶地看到简单的Hello World Go程序的大小,它是1.9MB!

为什么Go中这样一个简单程序的可执行文件是如此巨大?

解决方案

这个确切的问题出现在官方FAQ中: 为什么我的微不足道的程序如此庞大的二进制文件? 引用答案:


gc工具链中的连接符( 5l 6l 8l )做静态链接。因此,所有Go二进制文件都包含Go运行时以及支持动态类型检查,反射,甚至恐慌时间堆栈跟踪所需的运行时类型信息。



在Linux上使用gcc静态编译和链接的简单的Chello,world程序大约为750 kB,包括 printf 的实现。使用 fmt.Printf 的等效Go程序大约为1.9 MB,但包含更强大的运行时支持和类型信息。




因此,Hello World的本机可执行文件为1.9 MB,因为它包含一个提供垃圾回收,反射和许多其他功能的运行时(您的程序可能并未真正使用,但它在那里)。以及用于打印Hello World文本(以及它的依赖关系)的 fmt 包的实现。



现在尝试以下操作:向程序中添加另一个 fmt.Println(Hello World!Again)并再次编译它。结果不会是2个1.9MB,但仍然只有1.9 MB!是的,因为所有使用过的库( fmt 及其依赖项)和运行时都已添加到可执行文件中(因此只需添加几个字节即可打印第二个你刚刚添加的文本)。


I complied a hello world Go program which generated native executable on my linux machine. But I was surprised to see the size of the simple Hello world Go program, it was 1.9MB !

Why is it that the executable of such a simple program in Go is so huge?

解决方案

This exact question appears in the official FAQ: Why is my trivial program such a large binary?

Quoting the answer:

The linkers in the gc tool chain (5l, 6l, and 8l) do static linking. All Go binaries therefore include the Go run-time, along with the run-time type information necessary to support dynamic type checks, reflection, and even panic-time stack traces.

A simple C "hello, world" program compiled and linked statically using gcc on Linux is around 750 kB, including an implementation of printf. An equivalent Go program using fmt.Printf is around 1.9 MB, but that includes more powerful run-time support and type information.

So the native executable of your Hello World is 1.9 MB because it contains a runtime which provides garbage collection, reflection and many other features (which your program might not really use, but it's there). And the implementation of the fmt package which you used to print the "Hello World" text (plus its dependencies).

Now try the following: add another fmt.Println("Hello World! Again") line to your program and compile it again. The result will not be 2x 1.9MB, but still just 1.9 MB! Yes, because all the used libraries (fmt and its dependencies) and the runtime are already added to the executable (and so just a few more bytes will be added to print the 2nd text which you just added).

这篇关于Go的编译可执行文件的大小的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆