zoukankan      html  css  js  c++  java
  • 静动态库

    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. ");

              return 0;

          }

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

          if(dlerror()!=NULL)

          {

              printf("fun load error. ");

              return 0;

          }

          printf("%d ",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则会调用静态

  • 相关阅读:
    做题经验
    4906 删数问题
    1225 八数码难题
    1005 生日礼物
    1004 四子连棋 未完成
    1008 选数 2002年NOIP全国联赛普及组
    1068 乌龟棋 2010年NOIP全国联赛提高组
    2292 图灵机游戏
    实战数据结构(9)_单链表实现多项式的相乘
    最近招两个兼职的活(PHP和JSP)
  • 原文地址:https://www.cnblogs.com/qbmiller/p/3905382.html
Copyright © 2011-2022 走看看