GCC编程四个过程.doc
文本预览下载声明
GCC编程四个过程:预处理-编译-汇编-链接
在Linux下进行C语言编程,必然要采用GNU GCC来编译C源代码生成可执行程序。
一、GCC快速入门Gcc指令的一般格式为:Gcc [选项] 要编译的文件 [选项] [目标文件]其中,目标文件可缺省,Gcc默认生成可执行的文件名为:编译文件.out我们来看一下经典入门程序Hello World!# vi hello.c #include stdlib.h#include stdio.hvoid main(void){printf(hello world!\r\n);}用gcc编译成执行程序。#gcc -o hello hello.c该命令将hello.c直接生成最终二进制可执行程序a.out这条命令隐含执行了(1)预处理、(2)汇编、(3)编译并(4)链接形成最终的二进制可执行程序。这里未指定输出文件,默认输出为a.out。如何要指定最终二进制可执行程序名,那么用-o选项来指定名称。比如需要生成执行程序hello.exe那么#gcc hello.c -o hello.exe
二、GCC的命令剖析--四步走从上面我们知道GCC编译源代码生成最终可执行的二进制程序,GCC后台隐含执行了四个阶段步骤。GCC编译C源码有四个步骤:预处理----- 编译 ---- 汇编 ---- 链接现在我们就用GCC的命令选项来逐个剖析GCC过程。1)预处理(Pre-processing)在该阶段,编译器将C源代码中的包含的头文件如stdio.h编译进来,用户可以使用gcc的选项”-E”进行查看。用法:#gcc -E hello.c -o hello.i作用:将hello.c预处理输出hello.i文件。[root]# gcc -E hello.c -o hello.i[root]# lshello.c hello.i[root]# vi hello.i# 1 hello.c# 1 built-in# 1 command line# 1 hello.c# 1 /usr/include/stdlib.h 1 3# 25 /usr/include/stdlib.h 3# 1 /usr/include/features.h 1 3# 291 /usr/include/features.h 3# 1 /usr/include/sys/cdefs.h 1 3# 292 /usr/include/features.h 2 3# 314 /usr/include/features.h 3# 1 /usr/include/gnu/stubs.h 1 3# 315 /usr/include/features.h 2 3# 26 /usr/include/stdlib.h 2 3# 3 hello.c 2void main(void){printf(hello world!\r\n);}2)编译阶段(Compiling)第二步进行的是编译阶段,在这个阶段中,Gcc首先要检查代码的规范性、是否有语法错误等,以确定代码的实际要做的工作,在检查无误后,Gcc把代码翻译成汇编语言。用户可以使用”-S”选项来进行查看,该选项只进行编译而不进行汇编,生成汇编代码。选项 -S用法:[root]# gcc –S hello.i –o hello.s 作用:将预处理输出文件hello.i汇编成hello.s文件。[root@richard hello-gcc]# lshello.c hello.i hello.s如下为hello.s汇编代码[root@richard hello-gcc]# vi hello.s.file?? hello.c.section??? .rodata.LC0:.string hello world!\r\n.text.globl main.type?? main,@functionmain:pushl?? %ebpmovl??? %esp, %ebpsubl??? $8, %espandl??? $-16, %espmovl??? $0, %eaxsubl??? %eax, %espsubl??? $12, %esppushl?? $.LC0call??? printfaddl??? $16, %espmovl??? $0, %eaxleaveret.Lfe1:.size?? main,.Lfe1-main.ident GCC: (GNU) 3.2.2(Red Hat Linux 3.2.2-5)3)汇编阶段(Assembling
显示全部