歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux 如何使用GCC生成靜態庫和動態庫

Linux 如何使用GCC生成靜態庫和動態庫

日期:2017/3/1 10:28:58   编辑:Linux編程

在演示示例之前,我們先要明白以下幾個概念:

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

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. int main(void){
  3. int a = 3;
  4. int b = 6;
  5. showmsg("3+6:");
  6. show(add(a,b));
  7. showmsg("3-6:");
  8. show(sub(a,b));
  9. return 0;
  10. }

4、編譯源文件

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

  1. [root@localhost demo]# gcc -c main.c
Copyright © Linux教程網 All Rights Reserved