编译后的可执行文件很大的原因

编译后的可执行文件很大的原因

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

问题描述

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

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 !

为什么这么简单的 Go 程序的可执行文件那么大?

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?

引用答案:

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

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

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.

因此,您的 Hello World 的本机可执行文件为 1.9 MB,因为它包含一个运行时,该运行时提供垃圾收集、反射和许多其他功能(您的程序可能不会真正使用这些功能,但它就在那里).以及用于打印 Hello World" 文本(及其依赖项)的 fmt 包的实现.

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

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

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 编译后的可执行文件很大的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 04:17