(1)将testa.c testb.c 编译成动态库 libtest.so
testa.c:
#include <stdio.h>
void print_a(void)
{
printf("this is test_a\n");
}
testb.c:
#include <stdio.h>
void print_b(void)
{
printf("this is test_b\n");
}
编译:
$ gcc testa.c testb.c -fPIC -shared -o libtest.so
编译参数:
-shared 该选项指定生成动态连接库(让连接器生成T类型的导出符号表,有时候也生成弱连接W类型的导出符号),不用该标志外部程序无法连接。相当于一个可执行文件
-fPIC:表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的。
-L:表示要连接的库所在目录
-l:编译器查找动态连接库时有隐含的命名规则,即在给出的名字前面加上lib,后面加上.so来确定库的名称
(2)如果将编译的库放在/lib下即可直接使用,如果在自己的目录下需要输出LD_LIBRARY_PATH环境变量,以便动态库装载器能够找到需要的动态库:
$export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/decly/lib (指定库的目录,必须为绝对路径)
(3) 编译应用程序
test.h:
#ifndef TEST_H
#define TEST_H
void print_a(void);
void print_b(void);
#endif
test.c:
#include <stdio.h>
#include "test.h"
int main(void)
{
print_a();
print_b();
return 0;
}
编译:
$ gcc test.c -L. -ltest -o test
之后查看连接库是否成功 $ldd test
交叉编译步骤一致:
(1) $arm-linux-gcc testa.c testb.c -fPIC -shared -o libtest.so
(2) $arm-linux-gcc test.c -L. -ltest -o test
需要将 libtest.so 下载到开发板 /lib 下