15
ubuntu下制作动态链接库 so 文件并且调用
source link: https://blog.popkx.com/ubuntu-make-dynamic-library-and-use-it/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
ubuntu下制作动态链接库 so 文件并且调用
直接进入例子,将要编译成 so 文件的代码(testSo.c)贴出:
#include "stdio.h"
void lccprints(void)
{
printf("hello lcc, this is from so file.\n");
}
注意,不能有 main 函数,执行以下命令编译:
gcc testSo.c -fPIC -shared -o libtest.so
得到so文件。以下是调用部分,直接贴出代码:
#include "stdio.h"
#include "dlfcn.h"
typedef void (*myfun)(void);
void main()
{
myfun sofun;
printf("ready to work\n");
void *dp = dlopen("./libtest.so",RTLD_LAZY); // 动态链接库文件名,这里是同目录
if(dp==NULL)
printf("dlopen error\n");
sofun = dlsym(dp," lccprints "); // 入口函数名
if(dlerror() != NULL)
printf("dlerror\n");
sofun();
dlclose(dp);
}
gcc lccuseso.c -o testSo.out -L ./ -ldl
得到程序 testSo.out,执行结果如下
$ ./testSo.out
ready to work
hello lcc, this is from so file.
阅读更多: Linux笔记
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK