打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Unix/Linux C动态库的使用
Unix/Linux C动态库的使用
动态库的生成:
gcc -O -fpic -shared -o share.so share.c
有的gcc版本可以用"-G"替换"-shared"选项.

eg.使用动态库
#cc -O test.c ./share.so

eg.带路径编译
#cc -O test.c ./lib/share.so
当执行./a.out时,操作系统会自动在当前目录lib下查找share.so,若找不到程序将被杀.
当然也可以通过更改环境变量:
#LD_LIBRARY_PATH=./:share
#export LD_LIBRARY_PATH
#./a.out


例程:

dll1.c

#include <stdio.h>

int p = 1;

void print()
{
    printf("This is the first dll lib provided function: print().\n");

    return;
}

dll2.c

#include <stdio.h>

int p = 2;

void print()
{
    printf("This is the second dll lib provided function: print().\n");

    return;
}

implicit_test.c

int main (int argc, char *argv[])
{
    print();

    return 0;
}

explicit_test.c

#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

int main(int argc, char *argv[])
{
    void *handle; /* pointer of dll lib handle */
    void (*pfunc)();
    int *p;

    handle = dlopen("./dll1.so", RTLD_NOW); /* RTLD_LAZY mode, parsed symbol
                         when called */

    p = (int *)dlsym(handle, "p");
    if (p != NULL)
    {
        printf("p = %d.\n", *p);
    }

    if ( dlsym(handle, "pp") == NULL )    /* none exist variable pp */
    {
        printf( "%s\n", dlerror() );        /* print error, and clean */
    }

    pfunc = (void (*)())dlsym(handle, "print");
    if (pfunc != NULL)
    {
        pfunc();
    }

    dlclose(handle);

    return 0;
}

Makefile

LIB= -ldl

dll:
    gcc -O -fpic -shared -o dll1.so dll1.c
    gcc -O -fpic -shared -o dll2.so dll2.c
    # some version of gcc supports "-G" instead of "-shared" option

implicit_test:
    gcc -O -o implicit_test implicit_test.c ./dll1.so
    # argument: ./dll1.so, explicitly tell the os to search dll location.
    # if not told path, when running, os will implicitly search at default
    # +LD_LIBRARY_PATH=./:dll/

explicit_test:
    gcc -O -o explicit_test $(LIB) explicit_test.c

clean:
    rm -f dll1.so dll2.so implicit_test explicit_test


 
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
应用程序设计:在动态库中如何调用外部函数?
# C#调用已经使用Python训练好的神经网络做图片检测_c#调用tensorflow_LIU
C++Builder中动态库的链接问题
C语言中,函数不申明也能使用,但会出现warning: implicit declarat...
C 调用静态库和动态库
手把手教你在Windows下编译、使用开源库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服