Chinaunix首页 | 论坛 | 博客
  • 博客访问: 128532
  • 博文数量: 62
  • 博客积分: 1476
  • 博客等级: 上尉
  • 技术积分: 662
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-03 16:38
文章分类

全部博文(62)

文章存档

2010年(14)

2009年(48)

我的朋友

分类: C/C++

2009-12-25 21:31:46

动态库的生成:
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


阅读(740) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~