網(wǎng)站建設-縱橫網(wǎng)絡鄭州seo優(yōu)化外包公司
文章目錄
- 靜態(tài)庫
- 代碼
- 文件
- 過程
- 動態(tài)庫
- 代碼
- 過程
靜態(tài)庫
代碼
gcc -c test.c -o test.o //生成目標文件
ar crs libtest.a test.o //生成靜態(tài)庫
gcc main.c -L./ -ltest -o main_test //鏈接靜態(tài)庫
文件
靜態(tài)文件test.c
#include <stdio.h>void Hello(const char* arg)
{printf("Hello %s\n",arg);
}
源文件main.c
#include <stdio.h>extern void Hello(const char * arg);int main()
{Hello("world");return 0;
}
過程
step1:生成目標文件
gcc -c test.c -o test.o
step2:編譯(生成)靜態(tài)庫
ar crs libtest.a test.o
ls
libtest.a main.c test.c test.o
step3:鏈接靜態(tài)庫
gcc main.c -L./ -ltest -o main_test
ls
main_test libtest.a main.c test.c test.o
運行
./main_test
動態(tài)庫
代碼
1.創(chuàng)建動態(tài)庫
gcc -fPIC -Wall -c test.c //編譯為位置無關代碼(PIC)
gcc -shared -o libtest.so test.o //創(chuàng)建共享庫
2.編譯鏈接主程序
# 方法1 指定路徑
gcc main.c -o app -L./ -lmytest //生成可執(zhí)行文件app,但找不到動態(tài)庫
# 方法2 通過環(huán)境變量
pwd
export LIBRARY_PATH=$LIBRARY_PATH:(動態(tài)庫所在的路徑) //相當于-L的作用
3.設置系統(tǒng)尋找動態(tài)庫的路徑
# 方法1:指定路徑
cp libtest.so /usr/lib/ //系統(tǒng)會從這里找
./app# 方法2:環(huán)境變量
pwd //復制共享庫的路徑
sudo vim /etc/ld.so.conf //通過在/etc/ld.so.conf文件中添加共享庫的路徑來實現(xiàn)
sudo ldconfig
./app
過程
ls
main.c test.c
step1:生成目標文件
gcc -fPIC -Wall -c test.c -o test.o
ls
main.c test.c test.o
step2:創(chuàng)建共享庫
gcc -shared -o libtest.so test.o
ls
libtest.so main.c test.c test.o
step3:鏈接到可執(zhí)行文件
gcc main.c -o app -L./ -lmytest
ls
app libtest.so main.c test.c test.o
step4:設置路徑
把共享庫libtest.so復制到/usr/lib/下
或
在/etc/ld.so.conf文件中添加libtest.so所在的路徑(pwd)