静动态库

gcc test.c –fPIC –shared –o libtest.so

为了不需要动态加载动态库,在命令时需以lib开头以.so为后缀。

  1. 编译时加载动态库,  运行时还需要,不能移动位置

gcc main.c –L . –l test –o main

     –L:指明动态库所在的目录

      -l:指明动态库的名称,该名称是处在头lib和后缀.so中的名称,如上动态库libtest.so的l参数为-l test。

     测试:

     ldd test

        ldd 测试可执行文件所使用的动态库

2.      动态加载方式使用动态库

文件内容:

此处例子好些  http://www.cnblogs.com/Xiao_bird/archive/2010/03/01/1675821.html

//动态库的动态加载使用

#include <dlfcn.h>

 

int main()

{

      void *handle = NULL;

      int (*getMaxLen)(int *sel,int N);

      int sel[] = {1,2,5,4,5,8,6,5,9,5,4,5,4,1};

      handle = dlopen("./libtest.so",RTLD_LAZY);

      if(handle == NULL)

      {

          printf("dll loading error.\n");

          return 0;

      }

      getMaxLen = (int(*)(int *,int))dlsym(handle,"getMaxLen");

      if(dlerror()!=NULL)

      {

          printf("fun load error.\n");

          return 0;

      }

      printf("%d\n",getMaxLen(sel,15));

}

编译命令:

gcc –ldl test1.c –o test

gcc -o test test.c ./libmytools.so

  

====================================================

# ls
hello.c hello.h main.c
#
在来创建静态库文件libmyhello.a和动态库文件libmyhello.so。
# gcc -c hello.c
# ar cr libmyhello.a hello.o
# gcc -shared -fPCI -o libmyhello.so hello.o
# ls
hello.c hello.h hello.o libmyhello.a libmyhello.so main.c
#
通过上述最后一条ls命令,可以发现静态库文件libmyhello.a和动态库文件libmyhello.so都已经生成,并都在当前目录中。然后,我们运行gcc命令来使用函数库myhello生成目标文件hello,并运行程序

hello。
# gcc -o hello main.c -L. -lmyhello
# ./hello
./hello: error while loading shared libraries: libmyhello.so: cannot open shared object file: No such file or directory
#
从程序hello运行的结果中很容易知道,当Linux静态库和Linux动态库同名时, gcc命令将优先使用动态库

 

在最后一步,编译时, -static则会调用静态

posted @ 2014-11-11 10:21  義丨往昔灬miller  阅读(212)  评论(0编辑  收藏  举报