Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 用 GCC 產生靜態庫與動態庫的完整流程

一、四個先備概念

1. 靜態庫與動態庫的差別
依程式碼被載入的時機不同,Linux 下的庫分為兩類。靜態庫在編譯階段就被嵌入可執行檔,成為它的一部分,因此產物體積較大;動態庫(共享庫)則在程式執行時才被載入記憶體,可執行檔較小。動態庫還有一個顯著特點:多個程式同時使用同一個動態庫時,記憶體中只存在一份實例。

2. 命名規範
靜態庫以 .a 為副檔名,一般命名為 libxxx.a;動態庫以 .so 為副檔名,一般命名為 libxxx.so.major.minor,其中 major 是主版本號、minor 是副版本號。

3. 用 ldd 查看依賴的共享庫

ldd /usr/bin/vim

4. 動態庫的搜尋路徑
/lib、/usr/lib,以及 /etc/ld.so.conf 所配置的路徑。

二、庫的原始碼:demo.c

#include<stdio.h>

int add(int a, int b)
{
        return a+b;
}
int sub(int a, int b)
{
        return a-b;
}
void showmsg(const char * msg){
        printf("%s \n",msg);
}
void show(int num)
{
        printf("The result is %d \n",num);
}

三、標頭檔:demo.h

#ifndef DEMO_H
#define DEMO_H
int add(int a, int b);
int sub(int a, int b);
void showmsg(const char* msg);
void show(int num);
#endif

四、呼叫庫的程式:main.c

#include "demo.h"

int main(void){
        int a = 3;
        int b = 6;
        showmsg("3+6:");
        show(add(a,b));
        showmsg("3-6:");
        show(sub(a,b));
        return 0;
}

五、編譯

先編譯成目標檔:

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

接著打包成靜態庫(注意檔名必須以 lib 開頭、.a 結尾,連結時才能用 -l 簡寫):

ar rcs libdemo.a demo.o

編譯並連結靜態庫:

gcc main.o -L. -ldemo -o app_static

若要產生動態庫,改用 -shared 與 -fPIC:

gcc -shared -fPIC -o libdemo.so demo.c
gcc main.o -L. -ldemo -o app_shared
LD_LIBRARY_PATH=. ./app_shared

最後一步的 LD_LIBRARY_PATH 是關鍵:因為自製的 .so 不在系統搜尋路徑中,執行期必須明確告訴 loader 去哪裡找,否則會出現「error while loading shared libraries」。正式部署時,更恰當的做法是把庫放到 /usr/lib 後執行 ldconfig,或為它撰寫 /etc/ld.so.conf.d/ 下的設定檔。

Copyright © Linux教程網 All Rights Reserved