上一篇文章介紹了在windows下如何建立靜態連結庫和動態連結程式庫(http://blog.csdn.net/love_cppandc/article/details/8502773),這一篇介紹一下在linux下如何建立靜態連結庫和動態連結程式庫。
在linux下,靜態庫檔案是.a結尾,動態庫檔案是.so結尾。
1.靜態連結庫
首先建立3個檔案:static.h static.c test.c
static.c
int add( int a, int b ){return a + b;}
static.h
#ifndef LIB_H#define LIB_Hint add(int a,int b);#endif
test.c
#include <stdio.h>#include "static.h"int main(){printf( "%d\n", add(1,2) );return 0;}
命令如下:
# gcc -c static.c
這一步是產生static.o檔案
# ar cr libstatic.a static.o
這一步是產生靜態連結庫,特別需要注意的是庫名字必須是lib開頭,這個是必須的!
# gcc -o test test.c -L. -lstatic
這一步是將static庫與測試檔案test進行連結, -L.中的.代表目前的目錄
# ./test
結果為3
2.動態連結程式庫
建立三個檔案:dynamic.c dynamic.h test.c
dynamic.c
int add( int a,int b ){return a + b;}
dynamic.h
#ifndef DYNAMIC#define DYNAMICint add( int a,int b);#endif
test.c
#include <stdio.h>#include "dynamic.h"int main(){printf( "%d\n",add(1,2) );return 0;}
命令如下:
# gcc -c dynamic.c
這一步是產生dynamic.so檔案
# gcc -shared -fPCI -o libdynamic.so dynamic.so
這一步是產生動態連結程式庫
# gcc -o test test.c -L. -ldynamic
這一步是將dynamic庫與測試檔案test進行連結
# ./test
結果為3
總結:我們發現,調用靜態連結庫和動態連結程式庫的gcc命令完全一樣,並且可以確定的是,當存在同名的靜態庫和動態庫時,優先調用動態庫。