1. 动态链接库.so的编译
下面通过一个例子来介绍如何生成一个动态库。这里有一个头文件:so_test.h,三个.c文件:test_a.c、test_b.c、test_c.c,我们将这几个文件编译成一个动态库:libtest.so
// so_test.h
#include <stdio.h>
#include <stdlib.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");
}
将这几个文件编译成一个动态库:libtest.so
$ gcc test_a.c test_b.c test_c.c -fPIC -shared -o libtest.so
在代码路径上生成了libtest.so
2、动态库的链接
在1、中,我们已经成功生成了一个自己的动态链接库libtest.so,下面我们通过一个程序来调用这个库里的函数。程序的源文件为:test.c。
// test.c:
#include "so_test.h"
int main()
{
test_a();
test_b();
test_c();
return 0;
}
将test.c与动态库libtest.so链接生成执行文件test:
$ gcc test.c -L. -ltest -o test
测试是否动态连接,如果列出libtest.so,那么应该是连接正常了
$ ldd test
执行test,可以看到它是如何调用动态库中的函数的。
如果在打印出现的信息中,你发现有一行:libtest.so => not found,
bashrc添加.so的环境
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/compile_so
参考:https://www.cnblogs.com/blogernice/articles/9851042.html
https://www.cnblogs.com/wuchangming/articles/3084167.html