从静态库linux C++中打开一个动态库
dlopen a dynamic library from a static library linux C++
我有一个linux应用程序,它链接到一个静态库(.a),该库使用dlopen函数加载动态库(.so)
如果我将静态库编译为动态库并将其链接到应用程序,那么dlopen-it将按预期工作,但如果我如上所述使用它,则不会。
静态库不能使用dlopen函数加载共享库吗?
谢谢。
您尝试做的事情应该没有问题:
app.c:
#include "staticlib.h"
#include "stdio.h"
int main()
{
printf("and the magic number is: %dn",doSomethingDynamicish());
return 0;
}
staticlib.h:
#ifndef __STATICLIB_H__
#define __STATICLIB_H__
int doSomethingDynamicish();
#endif
staticlib.c:
#include "staticlib.h"
#include "dlfcn.h"
#include "stdio.h"
int doSomethingDynamicish()
{
void* handle = dlopen("./libdynlib.so",RTLD_NOW);
if(!handle)
{
printf("could not dlopen: %sn",dlerror());
return 0;
}
typedef int(*dynamicfnc)();
dynamicfnc func = (dynamicfnc)dlsym(handle,"GetMeANumber");
const char* err = dlerror();
if(err)
{
printf("could not dlsym: %sn",err);
return 0;
}
return func();
}
dynlib.c:
int GetMeANumber()
{
return 1337;
}
和构建:
gcc -c -o staticlib.o staticlib.c
ar rcs libstaticlib.a staticlib.o
gcc -o app app.c libstaticlib.a -ldl
gcc -shared -o libdynlib.so dynlib.c
第一行构建库
第二行将其打包到静态库中
第三个构建测试应用程序,在新创建的static和linux动态链接库(libdl)中进行链接
第四行构建即将动态加载的共享lib。
输出:
./app
and the magic number is: 1337
相关文章:
- 你能在链表中有一个动态数组和它的内存分配吗
- 从另一个动态链接库项目调用静态库函数
- 指向结构中的数组的指针,其中每个字段都是一个动态数组
- 无法在 CMake 中创建动态库并将其链接到另一个动态库?
- 如何创建一个动态数组,该数组可以保存从C++中派生的同一基类的所有不同对象
- 创建一个动态2D数组来存储类对象
- C++中的特征库有一个动态向量或矩阵吗
- 我需要一个在C 中具有一个动态维度的二维数组
- 在一个动态分配的数组的程序中分割故障
- 创建一个动态数组,包括汽车的年份和品牌,但无法保存我的第一个输出
- 使用 memcpy 将动态数组的内容复制到另一个动态数组上会产生运行时错误
- 在类成员函数中创建一个动态数组
- 当动态创建一个包含另一个动态创建的结构数组的结构数组时,内存管理
- 在C 中,正在将一个动态分配的对象传递给一个函数(总是)一个坏主意
- 在MacOS上编译一个动态库,库搜索路径指向同一目录(CMake)
- 声明一个动态大小数组
- 创建一个动态分配的std::vectors数组
- 从数组中删除多个元素并创建一个动态数组c++
- 如何根据另一个动态库链接动态库
- 返回一个动态数组