15

ubuntu下制作动态链接库 so 文件并且调用

 3 years ago
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.
neoserver,ios ssh client

ubuntu下制作动态链接库 so 文件并且调用

发表于 2018-07-14 21:07:16   |   已被 访问: 442 次   |   分类于:   Linux笔记   |   暂无评论

直接进入例子,将要编译成 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笔记


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK