1.建立max.c文件
int max(int n1, int n2, int n3)
{
int max_num = n1;
max_num = max_num < n2? n2: max_num;
max_num = max_num < n3? n3: max_num;
return max_num;
}
2.建立max.h文件
#ifndef __MAX_H__
#define __MAX_H__
int max(int n1, int n2, int n3);
#endif
3.建立test.c文件
#include <stdio.h>
#include <max.h>
int main(int argc, char *argv[])
{
int a = 10, b = -2, c = 100;
printf("max among 10, -2 and 100 is %d.\n", max(a, b, c));
return 0;
}
4.將max.c編譯成動態庫
gcc -fPIC -shared -o libmax.so max.c
第一種使用第三方庫的方法:
因爲 linux c 標準庫文件存放的路徑爲: /lib 和 /usr/lib
linux c 標準頭文件存放的路徑爲: /usr/include
將第三方的庫和頭文件分別放在以上兩個文件夾下,然後進行鏈接
gcc test.c -o test -lmax
./test
//運行成功
第一種方法改變了系統標準庫的內容,我們是不提倡的,所以我們指定庫和頭文件的路徑即可!
方法二:
gcc test.c -o test -I include_path -L lib_path -lyourlib
/*
include_path 改成你頭文件的目錄
lib_path 改成你動態庫文件的目錄
-lyourlib 改成l加上你要引用的庫文件名字
比如libmax.so就改成-lmax
*/
鏈接成成功!然而當運行的時候會報錯:
error while loading shared libraries: libmax.so: cannot open shared object file: No such file or directory
1.查看程序的庫依賴關係.看到libmax.so是找不到了
$ ldd test
linux-vdso.so.1 => (0x00007ffca89f0000)
libmax.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f8338902000)
/lib64/ld-linux-x86-64.so.2 (0x0000559a98721000)
原來:Linux是通過 /etc/ld.so.cache
文件搜尋要鏈接的動態庫的。
而 /etc/ld.so.cache
是 ldconfig 程序讀取 /etc/ld.so.conf
文件生成的。
(注意, /etc/ld.so.conf
中並不必包含 /lib
和 /usr/lib
,ldconfig
程序會自動搜索這兩個目錄)
如果我們把 libmax.so
所在的路徑添加到 /etc/ld.so.conf
中,再以root權限運行ldconfig
程序,更新/etc/ld.so.cache
,test
運行時,就可以找到libmax.so
。
$ ./test //運行成功!
但作爲一個簡單的測試例子,讓我們改動系統的東西,似乎不太合適。
還有另一種簡單的方法,就是爲a.out
指定 LD_LIBRARY_PATH
。
LD_LIBRARY_PATH=. ./test
程序就能正常運行了。LD_LIBRARY_PATH=.
是告訴 test
,先在當前路徑尋找鏈接的動態庫。