分享

Unix/Linux C动态库的使用

 蓝山逍遥屋 2011-09-13
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


 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多