【发布时间】:2014-09-02 14:36:07
【问题描述】:
Bjarne Stroustrup 在他的常见问题解答中说,当使用 gcc -O2 编译时,使用 C 和 C++ 的 hello world 的文件大小是相同的。
参考:http://www.stroustrup.com/bs_faq.html#Hello-world
我决定试试这个,这里是 C 版本:
#include <stdio.h>
int main(int argc, char* argv[])
{
printf("Hello world!\n");
return 0;
}
这里是 C++ 版本
#include <iostream>
int main(int argc, char* argv[])
{
std::cout << "Hello world!\n";
return 0;
}
我这里编译,大小不一样:
r00t@wutdo:~/hello$ ls
hello.c hello.cpp
r00t@wutdo:~/hello$ gcc -O2 hello.c -o c.out
r00t@wutdo:~/hello$ g++ -O2 hello.cpp -o cpp.out
r00t@wutdo:~/hello$ ls -l
total 32
-rwxr-xr-x 1 r00t r00t 8559 Sep 1 18:00 c.out
-rwxr-xr-x 1 r00t r00t 8938 Sep 1 18:01 cpp.out
-rw-r--r-- 1 r00t r00t 95 Sep 1 17:59 hello.c
-rw-r--r-- 1 r00t r00t 117 Sep 1 17:59 hello.cpp
r00t@wutdo:~/hello$ size c.out cpp.out
text data bss dec hex filename
1191 560 8 1759 6df c.out
1865 608 280 2753 ac1 cpp.out
我用\n 替换了std::endl,它使二进制文件更小。我认为这么简单的东西会被内联,但我很失望它不是。
哇,优化后的程序集有数百行程序集输出?我可以使用 sys_write 用 5 个汇编指令编写 hello world,所有额外的东西是怎么回事?为什么 C 会在堆栈上放一些额外的东西来设置?我的意思是,就像 50 字节的汇编与 8kb 的 C 一样,为什么?
【问题讨论】:
-
不,他没有这么说。他说 “2004 年,我在 Unix 上使用 gcc -O2 进行了测试,两个版本(iostreams 和 stdio)产生了相同的大小。”
-
您的问题具体是什么?此外,我认为声称 Bjarne 对此撒谎有点过分。有可能在旧系统上使用旧编译器,二进制文件确实具有相同的大小(即使在新系统上这不是真的。)
-
这根本不是“不清楚[他]在问什么”,你们这些缺乏想象力的巨魔。这是stackoverflow.com/q/10981140/560648的重复!
-
@LightnessRacesinOrbit 不,不是,文件大小相差 2 个数量级,并且在 Windows 上。 400 KB 值得担心,500 字节是学术性的。
-
尽管 OP 犯了一些错误,但这是一个具有一个或多个合法技术答案的合法问题。可以衡量和解释程序之间的大小差异。