在linux下編譯C/C++經(jīng)常會(huì)遇到谁榜,在這里做個(gè)筆記,也是因?yàn)閯e人問(wèn)我凡纳,我才想起來(lái)去查了下窃植,發(fā)現(xiàn)網(wǎng)上有這樣的玩意,但有些坑吧荐糜。
通過(guò)一個(gè)例子看看如何生成動(dòng)態(tài)庫(kù)巷怜。
頭文件:so_test.h
三個(gè).c文件:test_a.c test_b.c test_c.c
將這幾個(gè)文件一起編譯成動(dòng)態(tài)庫(kù)libtest.so
so_test.h
#include "stdio.h"
void test_a();
void test_b();
void test_c();
test_a.c
#include "so_test.h"
void test_a()
{
printf("this is in test_a...\n");
}
test_b.c
#include "so_test.h"
void test_b()
{
printf("this is in test_b...\n");
}
test_c.c
#include "so_test.h"
void test_c()
{
printf("this is in test_c...\n");
}
打開(kāi)命令行,編譯動(dòng)態(tài)庫(kù):libtest.so
$ gcc test_a.c test_b.c test_c.c -fPIC -shared -o libtest.so
2 動(dòng)態(tài)庫(kù)的鏈接
test.c
#include "so_test.h"
int main()
{
test_a();
test_b();
test_c();
return 0;
}
將test.c與動(dòng)態(tài)鏈接庫(kù)libtest.so鏈接生成執(zhí)行文件test:
gcc test.c -L. -ltest -o test
3 測(cè)試是否動(dòng)態(tài)鏈接暴氏,
$ ldd test
執(zhí)行test延塑,可以看到libtest.so not find
選區(qū)_003.png
將libtest.so放到usr/lib目錄下
前提是你必須有訪問(wèn)該文件的權(quán)限.如果要權(quán)限,可以將命令切換到usr下答渔,然后輸入命令
$ sudo chmod 775 lib
再次輸入命令
$ ldd test
得到如下結(jié)果:
選區(qū)_005.png
暫時(shí)就記錄到這里了关带,至于在android怎么玩我還在研究中。沼撕。宋雏。。