记录一下,这东西以前一直都不理解,今天按照最简单的方式创建了一下,记录在此。
首先创建四个目录
src:用于放置源文件
lib:用于放置动态库文件
include:用于放置头文件
bin:用于放置最后的可执行文件
现在include目录下创建mytestso.h文件
#include <stdio.h>
#include <stdlib.h>
int GetMax(int a, int b)
{
if (a >= b)
return a;
return b;
}
int GetInt(char* psztxt)
{
if (0 == psztxt)
return -1;
return atoi(psztxt);
}
保存好后,在这个目录下执行命令
gcc -fPIC -shared mytestso.c -Wl,-soname,-libhello.so.0 -o libhello.so.0.0.1
随后可以看到在这个目录下产生了一个名叫libhello.so.0.0.1的库文件,利用命令
mv libhello.so.0.0.0 ../lib
将这个库文件移动到lib目录下。并在lib目录下执行
ln -s libhello.so.0.0.1 libhello.so.0
以便创建一个软链接libhello.so.0.
至此,一个动态库文件已经全部搞好了,接下来就是如何调用它了。
切换到src目录下。创建文件mytest.c
保存,执行命令:#include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char* argv[]) { void* pdlhandle; char* pszerror; int (*GetMax)(int a, int b); int (*GetInt)(char* psztxt); void (*PrintVersion)(void); int a, b; char* psztxt = "1024"; // open mytestso.so pdlhandle = dlopen("../lib/libhello.so.0", RTLD_LAZY); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); } #if 1 // get GetMax func GetMax = dlsym(pdlhandle, "GetMax"); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); }
// get GetInt func GetInt = dlsym(pdlhandle, "GetInt"); pszerror = dlerror(); if (0 != pszerror) { printf("%s\n", pszerror); exit(1); } // call fun a = 200; b = 600; printf("max=%d\n", GetMax(a, b)); printf("txt=%d\n", GetInt(psztxt)); #endif // close mytestso.so dlclose(pdlhandle); }
gcc mytest.c -o ../bin/mytest -ldl
在bin目录下会生成一个mytest的可执行文件,进入到bin目录,执行:
./mytest
获得结果:
max=600
txt=1024
到了这一步,动态库的创建,动态加载过程已经都完毕了。
对动态库命名的规则,gcc参数的意义下篇文章再说吧。
参考文章:http://www.vckbase.com/index.php/wv/1209