zoukankan      html  css  js  c++  java
  • GCC生成动态库

    文件目录组织

    src
    
    |--mmath.c
    
    |--mmath.h
    
    |--app.c
    
    |--makefile

    mmath.h文件内容

    #pragma once
    
    int add(int a,int );

    mmath.c文件内容

    #include <stdio.h>
    
    int add(int a,int b){
        return a + b;
    }

    app.c文件内容

    #include <stdio.h>
    #include "mmath.h"
    
    int main()
    {
        int x = add(3,4);
        printf("3 + 4 = %d
    ",x);
    }

    mingw下makefile内容

    app : app.c
        gcc -o $@ $^ -L. -lmmath
    
    mmath : mmath.c
        gcc -shared -o $@.dll $^ -Wl,--out-implib,$@.lib

    mingw下执行

    user@host MINGW64 /d/git/mmath/ (dev)
    $ make mmath
    gcc -shared -o mmath.dll mmath.c -Wl,--out-implib,mmath.lib
    
    user@host MINGW64 /d/git/mmath/ (dev)
    $ make
    gcc -o app app.c -L. -lmmath
    
    user@host MINGW64 /d/git/mmath/ (dev)
    $ ./app.exe
    3 + 4 = 7
    
    user@host MINGW64 /d/git/mmath/ (dev)
    $ ls
    app.c app.exe* makefile mmath.c mmath.dll* mmath.h mmath.lib

    ubuntu下makefile

    app : app.c
           gcc -o $@ $^ -L. -lmmath
    mmath : mmath.c
            gcc -shared -o lib$@.so $^
    clean:
           rm -rf app
           rm -rf lib*

    ubuntu下执行

    user@host:~/mmath$ make mmath
    gcc -fPIC -shared -o libmmath.so mmath.c
    user@host:~/mmath$ make
    gcc -o app app.c -L./ -lmmath
    user@host:~/mmath$ ./app
    ./app: error while loading shared libraries: libmmath.so: cannot open shared object file: No such file or directory

    这个时候会报错说找不到libmmath.so,那么gcc是如何查找动态链接库的呢?

    l  如果安装在/lib或者/usr/lib下,那么ld默认能够找到,无需其他操作。

    l  如果安装在其他目录,需要将其添加到/etc/ld.so.cache文件中,步骤如下:

        n  编辑/etc/ld.so.conf文件,加入库文件所在目录的路径

        n  运行ldconfig ,该命令会重建/etc/ld.so.cache文件

    下面修改makefile添加install,将创建的动态库复制到/usr/lib下面,然后运行测试程序。

    app : app.c
           gcc -o $@ $^ -L. -lmmath
    mmath : mmath.c
            gcc -shared -o lib$@.so $^
    install :
            cp libmmath.o /usr/lib/        
    clean:
           rm -rf app
           rm -rf lib*

     再次执行,成功了!

    user@host:~/mmath$ make clean
    rm -rf app
    rm -rf lib*
    user@host:~/mmath$ make mmath
    gcc -fPIC -shared -o libmmath.so mmath.c
    user@host:~/mmath$ sudo make install
    cp libmmath.so /usr/lib/
    user@host:~/mmath$ make
    gcc -o app app.c -L./ -lmmath
    user@host:~/mmath$ ./app
    3 + 4 = 7
    user@host:~/mmath$
  • 相关阅读:
    LeetCode——面试题57
    翻译——5_Summary, Conclusion and Discussion
    LeetCode——114. 二叉树展开为链表
    LeetCode——1103. 分糖果 II
    LeetCode——337. 打家劫舍 III
    LeetCode——994. 腐烂的橘子
    Python——潜在会员用户预测
    Vue中div高度自适应
    webpack中使用vue-resource
    Mint UI组件库 和 Mui
  • 原文地址:https://www.cnblogs.com/Netsharp/p/13201336.html
Copyright © 2011-2022 走看看