在Bjarne Stroustrup的常见问题解答(FAQ)中,他说使用gcc -O2编译时,使用C和C++编写的Hello World文件的文件大小是相同的。
参考资料:http://www.stroustrup.com/bs_faq.html#Hello-world 我决定尝试一下,这是C语言版本:
参考资料: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
我将 std::endl
替换为 \n
,这样的修改使二进制文件更小了。本来认为这么简单的修改可以被内联,但结果让我失望了。
此外,优化编译后的汇编代码有数百行?我可以使用 sys_write 只用 5 条汇编指令编写出一个 hello world 程序,为什么会有这么多额外的东西呢?为什么 C 语言要在堆栈上存储这么多额外信息进行设置?相比之下,C 语言需要 8KB 的代码,而汇编只需要大约 50 字节,为什么呢?