在用 C 编程了一段时间之后,我决定终于开始学习 C++。这有点困扰我,因为 C 中的标准“hello world”通常是 ~16KB,包括你的编译器在那里抛出的所有垃圾。 (使用标准输入输出)
但是,当我创建一个执行 hello world 的 C++ 可执行文件时,该文件约为 470KB!我继续使用 cstdio 而不是 iostream,认为它会有所作为并且确实如此。
我的问题是: 当我包含 iostream 时,为什么我的可执行文件的大小会爆炸?
编辑:我正在使用 G++(使用 Dev-CPP IDE,但我可以弄清楚如何添加 CL 参数)
最佳答案
一句话,符号。
C++ 标准库为您的程序引入了很多符号,因为大多数库主要存在于头文件中。
在 Release模式下重新编译您的程序并且不使用调试符号,您可以很容易地期望该程序明显更小。 (如果你去掉符号,会更小。)
作为这一事实的快速演示,请观察:
$ cat hello.c
#include <stdio.h>
int main() {
printf("%s\n", "Hello, world!");
return 0;
}
$ cat hello.cpp
#include <iostream>
int main() {
std::cout << "Hello, world!\n";
return 0;
}
$ gcc hello.c -o hello-c
$ g++ hello.cpp -o hello-cpp
$ gcc hello.c -ggdb -o hello-c-debug
$ g++ hello.cpp -ggdb -o hello-cpp-debug
$ gcc hello.c -s -o hello-c-stripped
$ g++ hello.cpp -s -o hello-cpp-stripped
$ gcc hello.c -s -O3 -o hello-c-stripped-opt
$ g++ hello.cpp -s -O3 -o hello-cpp-stripped-opt
$ ls -gG hello*
-rwxr-xr-x 1 6483 Nov 14 15:39 hello-c*
-rw-r--r-- 1 79 Nov 14 15:38 hello.c
-rwxr-xr-x 1 7859 Nov 14 15:40 hello-c-debug*
-rwxr-xr-x 1 7690 Nov 14 15:39 hello-cpp*
-rw-r--r-- 1 79 Nov 14 15:38 hello.cpp
-rwxr-xr-x 1 19730 Nov 14 15:40 hello-cpp-debug*
-rwxr-xr-x 1 5000 Nov 14 15:45 hello-cpp-stripped*
-rwxr-xr-x 1 4960 Nov 14 15:41 hello-cpp-stripped-opt*
-rwxr-xr-x 1 4216 Nov 14 15:45 hello-c-stripped*
-rwxr-xr-x 1 4224 Nov 14 15:41 hello-c-stripped-opt*
我无法解释为什么使用 G++ 构建的 Windows 程序会产生如此大的可执行文件,但在任何其他平台上,符号是大文件大小的主要驱动因素。我目前无法访问 Windows 系统,因此无法进行测试。
关于c++ - 编译的 C++ 可执行文件巨大?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4178910/