gcc 编译过程详解

1,编译过程:一个C/C++文件要经过预处理,编译,汇编和连接等4步才能变成可执行文件。    
1.1 预处理     
C/C++源文件中,以“#”开头的命令被称为预处理,如包含命令“#include”宏定义等。预处理就是要将包含include的文件插入原文件中,将宏定义展开,根据条件编译选择要使用的代码,最后输出一个.i文件。    
如下将生成.i文件。
book@www.100ask.org:~/myFile$ gcc -E  -o helloWorld.i   helloWorld.c 
book@www.100ask.org:~/myFile$ ls
helloWorld.c  helloWorld.i

1.2 编译    
 编译就是把C/C++代码翻译成汇编代码,所用到的工具为cc1        
     book@www.100ask.org:~/myFile$ gcc   -S  -o helloWorld.s helloWorld.i
book@www.100ask.org:~/myFile$ ls
helloWorld.c  helloWorld.i  helloWorld.s
1.3 汇编    
汇编就是将第二步的汇编代码翻译成符合一定格式的机器码,在linux系统上一般表现为ELF目标文件。反汇编就是将机器码转化为汇编代码,这在调试程序的时候,常常用到。   
book@www.100ask.org:~/myFile$ gcc -c -o helloWorld.o helloWorld.s
book@www.100ask.org:~/myFile$ ls
helloWorld.c      helloWorld.i  helloWorld.o  helloWorld.s

1.4 连接    
连接就是将上步生成的OBJ文件和系统库OBJ文件,库文件连接起来,最终生成可执行文件。    
book@www.100ask.org:~/myFile$ gcc -o helloWorld  helloWorld.o
book@www.100ask.org:~/myFile$ ls
helloWorld  helloWorld.c  helloWorld.i  helloWorld.o  helloWorld.s
我们查看相应文件大小可知,在预处理,编译,汇编,连接的过程中,编译器自动加了很多相应的指令        
helloWorld  helloWorld.c  helloWorld.i  helloWorld.o  helloWorld.s
book@www.100ask.org:~/myFile$ ls -l
total 44
-rwxrwxr-x 1 book book  8608 4月  29 15:48 helloWorld
-rw-rw-r-- 1 book book   227 4月  29 15:39 helloWorld.c
-rw-rw-r-- 1 book book 17124 4月  29 15:40 helloWorld.i
-rw-rw-r-- 1 book book  1504 4月  29 15:47 helloWorld.o
-rw-rw-r-- 1 book book   452 4月  29 15:45 helloWorld.s
如果我们采用静态编译的方法,那么需要占用多大的空间?        
book@www.100ask.org:~/myFile$ gcc -static -o  helloWorld_static   helloWorld.o
book@www.100ask.org:~/myFile$ ls -l 
total 936
-rwxrwxr-x 1 book book   8608 4月  29 15:48 helloWorld
-rw-rw-r-- 1 book book    227 4月  29 15:39 helloWorld.c
-rw-rw-r-- 1 book book  17124 4月  29 15:40 helloWorld.i
-rw-rw-r-- 1 book book   1504 4月  29 15:47 helloWorld.o
-rw-rw-r-- 1 book book    452 4月  29 15:45 helloWorld.s
-rwxrwxr-x 1 book book 912704 4月  29 15:52 helloWorld_static
由此可见,采用静态编译所生成的 helloWorld_static可执行文件是动态编译 helloWorld(默认就是采用动态编译)百倍。    




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值