gcc 编译一个C文件的过程分析,动态链接生成

来源:互联网 发布:主图BS点指标公式源码 编辑:程序博客网 时间:2024/05/20 14:14

#gcc hello.c

该命令将hello.c直接生成最终二进制可执行程序a.out

这条命令隐含执行了(1)预处理、(2)汇编、(3)编译并(4)链接形成最终的二进制可执行程序。这里未指定输出文件,默认输出为a.out。

 

GCC编译C源码有四个步骤:

预处理-----> 编译 ----> 汇编 ----> 链接

现在我们就用GCC的命令选项来逐个剖析GCC过程。

1)预处理(Pre-processing)

  在该阶段,编译器将C源代码中的包含的头文件如stdio.h编译进来,用户可以使用gcc的选项”-E”进行查看。

用法:#gcc -E hello.c -o hello.i

作用:将hello.c预处理输出hello.i文件。

选项 -S

用法:[root]# gcc –S hello.i –o hello.s

作用:将预处理输出文件hello.i汇编成hello.s文件。

[root@richard hello-gcc]# ls

hello.c  hello.i  hello.s

3)汇编阶段(Assembling)

  汇编阶段是把编译阶段生成的”.s”文件转成二进制目标代码.

选项 -c

用法:[root]# gcc –c hello.s –o hello.o

作用:将汇编输出文件test.s编译输出test.o文件。

[root]# gcc -c hello.s -o hello.o

[root]# ls

hello.c  hello.i  hello.o  hello.s

4)链接阶段(Link)

无选项链接

用法:[root]# gcc hello.o –o hello.exe

作用:将编译输出文件hello.o链接成最终可执行文件hello.exe。

[root]# ls

hello.c  hello.exe  hello.i  hello.o  hello.s

[root@localhost Gcc]# ./hello

Hello World!

在这里涉及到一个重要的概念:函数库。

[root]# ldd hello.exe

libc.so.6 => /lib/tls/libc.so.6 (0x42000000)

/lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)

函数库一般分为静态库和动态库两种。静态库是指编译链接时,把库文件的代码全部加入到可执行文件中,因此生成的文件比较大,但在运行时也就不再需要库文件了。其后缀名一般为”.a”。动态库与之相反,在编译链接时并没有把库文件的代码加入到可执行文件中,而是在程序执行时由运行时链接文件加载库,这样可以节省系统的开销。动态库一般后缀名为”.so”,如前面所述的libc.so.6就是动态库。gcc在编译时默认使用动态库。

 

test.h

  1. #ifndef  _TEST_H  
  2. #define  _TEST_H  
  3.   
  4. int add(int a, int b);  
  5. #endif  

 

test.c

  1. #include "test.h"  
  2.   
  3. int add(int a, int b)  
  4. {  
  5.     return a + b;  

我们想要生成动态库,要做的工作其实非常简单,输入gcc -shared -fPIC -o libtest.so test.c即可

hello.c

  1. #include <stdio.h>  
  2. #include "test.h"  
  3.   
  4. int main()  
  5. {  
  6.     printf("%d\n", add(2, 3));  
  7.     return 1;  
  8. }

 

输入gcc hello.c -o  hello ./libtest.so。然后输入./hello

就行了。

 

 

 

 

 

 

 

 

 

原创粉丝点击