编写GNUGCC下的动态链接库程序
先来一个简单的编译时动态链接的例子
创建文件function.h
#include <stdlib.h> #define int_t intint_t foo(int_t i, int_t j);
创建文件function.c
#include "function.h" int_t foo(int_t i, int_t j){ if (i > j) return i; else return j;}创建文件main.c
#include "function.h" int_t foo(int_t i, int_t j){ if (i > j) return i; else return j;}先编译生成动态链接库文件
gcc -shared -fPIC function.c -o function.so
-shared表示生成共享的目标文件,这种目标文件可以与其它相同标识(同为-fPIC或同为-fpic)的目标文件链接成可执行文件
-fPIC表示生成position-independent code(平台无关的代码)用于共享库。这种code在访问所有常量地址时,会通过系统的global offset table(GOT)。当程序开始运行时,动态加载器会去解析那个GOT。注,-fPIC比-fpic生成的代码要大,所以不用担心GOT大小超过限制的问题
最后将主程序与动态链接库链接
gcc -o main -L ./ main.c function.so
-L表示链接库的地址
注意运行时要把function.so放到/usr/lib之下
运行时动态链接的例子
编辑文件dltest.c
#include <stdlib.h>#include <dlfcn.h>--------------------------void main()-{- int (*func)(int i, int j);- void *dlhandle;- char *dlError;- printf("hello! I'm main.c\n"); dlhandle = dlopen("./function.so", RTLD_LAZY);- if (dlhandle == NULL) { printf("dlhandle error\n"); } dlError = dlerror();- func = dlsym(dlhandle, "foo");- printf("%i\n", func(10, 30)); dlclose(dlhandle);}同上文一样,生成function.so文件,只不过这个文件应该不用扔到/usr/lib中
链接文件
gcc -o dltest -ldl dltest.c
提一句选项-ldl的意思并不是说有一个gcc选项叫-ldl,而是-l dl的意思,把dl库链接过来,而这个dl库应该是包含了dlfcn.h等等文件吧。