dlopen linux 实例_dlopen从静态库linux C ++的动态库

I've a linux application that links against a static library (.a) and that library uses the dlopen function to load dynamic libraries (.so)

If I compile the static library as dynamic and link it to the application, the dlopen it will work as expected, but if I use it as described above it won't.

Can't a static library uses the dlopen function to load shared libraries?

Thanks.

解决方案

There should be no problem with what you're trying to do:

app.c:

#include "staticlib.h"

#include "stdio.h"

int main()

{

printf("and the magic number is: %d\n",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: %s\n",dlerror());

return 0;

}

typedef int(*dynamicfnc)();

dynamicfnc func = (dynamicfnc)dlsym(handle,"GetMeANumber");

const char* err = dlerror();

if(err)

{

printf("could not dlsym: %s\n",err);

return 0;

}

return func();

}

dynlib.c:

int GetMeANumber()

{

return 1337;

}

and build:

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

First line builds the lib

second line packs it into a static lib

third builds the test app, linking in the newly created static, plus the linux dynamic linking library(libdl)

fourth line builds the soon-to-be-dynamically-loaded shared lib.

output:

./app

and the magic number is: 1337

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值