@breakerthb
2017-05-08T06:54:01.000000Z
字数 1519
阅读 1331
Linux
// getmaxlen.h
#ifndef _GETMAXLEN_H_
#define _GETMAXLEN_H_
int getMax(int a, int b);
#endif
// getmaxlen.c
#include "getmaxlen.h"
int getMax(int a, int b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
gcc getmaxlen.c -fPIC -shared -o libmax.so
由以上命令生成动态库libmax.so
,为了不需要动态加载动态库,在命令时需以lib
开头以.so
为后缀。
A | |
---|---|
-fPIC | 表示编译为位置独立的代码,不用此选项的话编译后的代码是位置相关的所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的 |
-shared | 指明编译成动态库 |
// test.c
#include <stdio.h>
#include "getmaxlen.h"
int main()
{
int a = 5;
int b = 3;
printf("The max is %d\n", getMax(a, b));
return 0;
}
gcc test.c -L. -lmax -o test
A | |
---|---|
-L | 指明动态库所在的目录 |
-l | 指明动态库的名称,该名称是处在头lib 和后缀.so 中的名称,如上动态库libtest.so的l参数为-lmax。 |
ldd test
ldd 测试可执行文件所使用的动态库
./test
结果如下:
The max is 5
一般情况下,调用程序和so文件需要在同一个目录下,这样才能保证动态链接时能够找到。如果不在同一个目录,需要通过配置LD_LIBRARY_PATH
环境变量指定寻找路径。
比如:
gcc getmaxlen.c -fPIC -shared -o lib/libmax.so
gcc test.c -Llib -lmax -o test
执行一下:
./test
可以看到如下结果:
如果需要它不在同一个目录执行,有另一个方法:
gcc getmaxlen.c -fPIC -shared -o lib/libmax.so
gcc test.c -Llib -lmax -Wl,-rpath=lib -o test
-Wl,-rpath=为程序指定链接库的位置。
//动态库的动态加载使用
#include <stdio.h>
#include <dlfcn.h>
int main()
{
void *handle = NULL;
int (*getMax)(int a, int b);
handle = dlopen("./libmax.so", RTLD_LAZY);
if(handle == NULL)
{
printf("dll loading error.\n");
return 0;
}
getMax = (int(*)(int,int))dlsym(handle, "getMax");
if (getMax==NULL)
{
printf("%s:dlsym:'%s'\n","getMaxLen",dlerror());
return 0;
}
printf("%d\n",getMax(5, 15));
return 0;
}
编译命令:
gcc test.c -ldl -o test
-ldl:使用动态库相关函数需使用该参数
注意:
另:使用c++时,so文件在声明是要加extern"C",才能正确获取函数地址.否则,在dlsym可能的错误:找不到函数(undefined symbol).
getmaxlen.h 中声明如:
extern "C" int getMaxLen(int *sel,int N);