zoukankan      html  css  js  c++  java
  • Linux第一个动态库

    动态库一般以.so结尾,就是shared object的意思.

     其基本生成步骤为   ⑴编写函数代码   ⑵编译生成动态库文件,要加上 -shared 和 -fpic 选项 ,
         库文件名以lib开头, 以.so 结尾。     -fpic 使输出的对象模块是按照可重定位地址方式生成的。-shared指定把对应的源文件生成对应的动态链接库文件libstr.so文件。使用方式分为两种: 隐式调用和显示调用  隐式调用类似于静态库的使用,但需修改动态链接库的配置文件/etc/ld.so.conf;  显示调用则是在主程序里使用dlopen、dlsym、dlerror、dlclose等系统函数。
     
    第一个简单的动态库编写:
     
    -----------func.h----------- 
     
    #include <stdio.h>
    void ShowHello();
     
    ----------func.c-----------
     
    #include "func.h"
    void ShowHello()
    {
        printf("show hello func called ");
    }
    gcc -fpic -shared -o libTest2.so  func.c   生成 动态库 libTest2.so
     
    动态库显示调用:
     
    ------------uselib.c-----------------------
    #include <dlfcn.h>
    #include "func.h" 
    #include <stdio.h>
    int main()
    {
        void(*pFun)();
        void* pdHandle=dlopen("/mnt/hgfs/LinuxShare/cplus/TestLib2/libTest2.so",RTLD_LAZY);
        if(!pdHandle)
        {
    printf("dlopen failed ");
    return -1;
        }
        char* errCh=dlerror();
        if(NULL!=errCh)
        {
           printf("dlerror ");
           return -1;
        }
        pFun=dlsym(pdHandle,"ShowHello");
        errCh=dlerror();
        if(NULL!=errCh)
        {
           printf("dlerror2 ");
           return -1;
        }
        (*pFun)();
        dlclose(pdHandle);
        return 0;
    }
     
    通过命令  gcc -o uselib -ldl uselib.c  编译生成可执行文件 uselib    -ldl  选项表示 用到了共享库
     
    ./uselib  执行 可打印出    show hello func called  

    ————————————————
    版权声明:本文为CSDN博主「mtour」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/mtour/article/details/8274200

  • 相关阅读:
    飞入飞出效果
    【JSOI 2008】星球大战 Starwar
    POJ 1094 Sorting It All Out
    POJ 2728 Desert King
    【ZJOI 2008】树的统计 Count
    【SCOI 2009】生日快乐
    POJ 3580 SuperMemo
    POJ 1639 Picnic Planning
    POJ 2976 Dropping Tests
    SPOJ QTREE
  • 原文地址:https://www.cnblogs.com/bruce1992/p/14454970.html
Copyright © 2011-2022 走看看