zoukankan      html  css  js  c++  java
  • linux gcc 编译动态类库(.so)和静态类库(.a)

    linux gcc 编译动态类库(.so)和静态类库(.a)

    我的编译环境 ubuntu desktop 16.04

    一:测试代码

    测试有3个文件:AB.h,AB.c,test.c

    //AB.h
    void hello();
    
    
    
    //AB.c
    #include <stdio.h>
    
    void hello()
    {
        printf("hello from AB.c 
    ");
    }
    
    
    
    //test.c
    #include <stdio.h>
    #include "AB.h"
    
    void main(void)
    {
        printf("it is main
    ");
        hello();
    }
    View Code

    使用gcc, 编译运行,显示结果:

    cocoa@ubuntu:~/Desktop/demo$ gcc AB.c test.c
    cocoa@ubuntu:~/Desktop/demo$ ./a.out
    it is main
    hello from AB.c

    二:gcc 编译静态类库 .a

    //编译点o文件
    cocoa@ubuntu:~/Desktop/demo$ gcc -c AB.c 
    //编译为AB.o文件
    cocoa@ubuntu:~/Desktop/demo$ ls
    AB.c  AB.h  AB.o  a.out  test.c
    //打包成.a 文件
    cocoa@ubuntu:~/Desktop/demo$ ar -crv libAB.a AB.o 
    a - AB.o
    //编译测试程序,测试libAB.a
    cocoa@ubuntu:~/Desktop/demo$ gcc -o testlibA test.c libAB.a 
    //测试程序 testlibA
    cocoa@ubuntu:~/Desktop/demo$ ls
    AB.c  AB.h  AB.o  a.out  libAB.a  test.c  testlibA
    //运行测试,输出结果与上面一致
    cocoa@ubuntu:~/Desktop/demo$ ./testlibA 
    it is main
    hello from AB.c 
    cocoa@ubuntu:~/Desktop/demo$ 

    三:gcc 编译动态类库 .so

    //编译AB.c 为动态类库libAB.so
    cocoa@ubuntu:~/Desktop/demo$ gcc -shared -o libAB.so -fPIC AB.c 
    //查看
    cocoa@ubuntu:~/Desktop/demo$ ls
    AB.c  AB.h  AB.o  a.out  libAB.a  libAB.so  test.c  testlibA
    //编译测试程序testSO,并链接当前目录下的libAB.so
    cocoa@ubuntu:~/Desktop/demo$ gcc -o testSO test.c -lAB -L.
    //设置一下动态类库路径
    cocoa@ubuntu:~/Desktop/demo$ export LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH
    //运行测试程序,结果与上述一致
    cocoa@ubuntu:~/Desktop/demo$ ./testSO 
    it is main
    hello from AB.c 
    cocoa@ubuntu:~/Desktop/demo$ 

    对外提供,只需要把 AB.h 和libAB.a 或libAB.so 即可;

    参考:http://www.cnblogs.com/ymy124/archive/2012/04/13/2446434.html

  • 相关阅读:
    spawn-fcgi
    JSP EL表达式
    关于订阅号和自定义菜单的关系问题
    微信公众平台开发(74) 用户分组管理
    微信公众平台开发(73) 客服接口发送客服消息
    用数据分析寻找下一位苍井空
    微商城
    微信支付体验
    微信公众平台开发(72)第三方接口
    微信公众平台开发(71)OAuth2.0网页授权
  • 原文地址:https://www.cnblogs.com/cocoajin/p/5521094.html
Copyright © 2011-2022 走看看