Linux 如何使用GCC生成静态库和动态库


在演示示例之前,我们先要明白以下几个概念:

1、静态库与动态库的区别:

根据代码被载入的时间不同,linux下库分为两种:静态库和动态库(也叫共享库)。静态库,在编译时,已经被载入到可执行程序中,静态库成为可执行文件的一部分,因此可可执行程序文件比较大。动态库,可执行程序在执行时,才被引用到内存,因此可执行程序文件小。动态库,一个显著特点就是:当多个程序调用同个动态库时,内存中只有一个动态库实例。

2、库命名规范

a)静态库以.a 为后缀,动态库以.so为后缀

b)静态库名字一般是libxxx.a,其中xxx 是库的名字;动态库的名字一般是libxxx.so.major.minor 其中xxx是库名,majar 是主版本号,minor是副版本号

3、通过ldd查看程序所依赖的共享库

查看vim所依赖的共享库:ldd /usr/bin/vim

4、程序查找动态库的路径

/lib 和 /usr/lib 及 /etc/ld.so.conf配置的路径下

有了上面的简单介绍,下面,我们开始给出代码示例了:

1、库源文件:demo.c

  1. #include<stdio.h>  
  2.   
  3. int add(int a, int b)  
  4. {  
  5.         return a+b;  
  6. }  
  7. int sub(int a, int b)  
  8. {  
  9.         return a-b;  
  10. }  
  11. void showmsg(const char * msg){  
  12.         printf("%s \n",msg);  
  13. }  
  14. void show(int num)  
  15. {  
  16.         printf("The result is %d \n",num);  
  17. }  

2、库头文件: demo.h

  1. #ifndef DEMO_H  
  2. #define DEMO_H  
  3. int add(int a, int b);  
  4. int sub(int a, int b);  
  5. void showmsg(const char* msg);  
  6. void show(int num);  
  7. #endif  

3、调用库源文件:main.c

  1. #include "demo.h"  
  2.   
  3. int main(void){  
  4.         int a = 3;  
  5.         int b = 6;  
  6.         showmsg("3+6:");  
  7.         show(add(a,b));  
  8.         showmsg("3-6:");  
  9.         show(sub(a,b));  
  10.         return 0;  
  11. }  

4、编译源文件

  1. [root@localhost demo]# gcc -c demo.c  

 

  1. [root@localhost demo]# gcc -c main.c  
  • 1
  • 2
  • 3
  • 下一页

相关内容