一. 动态库的书写
头文件test.h:
#ifdef TEST_H#define TEST_H
#include <stdio.h>
#include <stdlib.h>
int add(int a, int b);
int Less(int a ,int b);
#endif
实现文件test.c:
#include "test.h"
int add(int a,int b){
return a+b;
}
int Less(int a,int b){
return a-b;
}
二、编译动态库
gcc tes.c -fPIC -shared -o libtest.so //如果有多个.c 文件,就把所有的.c文件进行编译
隐式链接(编译时链接)
使用gcc main.c -L. -ltest -o test进行编译。
-L:添加库文件的搜索路径
-l:指定需要链接的库。该名称是处在头lib和后缀.so中的名称,如上动态库libtest.so的l参数为-l test
在执行隐式链接的程序之前要注意设置LD_LIBRARY_PATH环境变量,或者把前面生成的libtest.so复制到系统路径下,否则会找不到动态库。
$ ./test
./test: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
$ export LD_LIBRARY_PATH=.
$ ./test
或者把编译好的动态库放到/usr/lib 中去
本文介绍了如何编写简单的动态库代码,包括头文件和实现文件的内容,并详细解释了使用GCC编译器进行动态库编译及链接的过程。此外,还说明了如何设置环境变量以确保动态链接库可以被正确加载。
1191

被折叠的 条评论
为什么被折叠?



