IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]做一个动态链接库

    lincyang发表于 2015-10-31 14:13:23
    love 0

    写此文的目的是验证将C代码编译成so,随后将其放到Android平台供上层应用调用。这个库的名称为shooter。
    动态链接库也叫共享库(shared object),将源码编译成二进制文件,在程序运行时动态的加载它。我们会把一些常用的通用的方法做成库以so的形式发布,
    好处是有效的知识管理和有效的隐私保护。

    libshooter.so

    目前shooter只暴露一个A方法,头文件shooter.h如下:

    //so demo
    
    #ifndef SHOOTER_H
    #define SHOOTER_H
    
    #ifdef __cplusplus
    extern "C" {
    #endif
    
    int A(int a);
    
    #endif

    A方法完成了在1到100的是个随机数中找出最小的那个返回。
    源文件shooter.c如下:

    #include "shooter.h"
    #include "time.h"
    #include <stdio.h>
    
    void bubble_sort(int *array,int n) {
        int i,j,tmp;
        for(i=0;i<n-1;i++) {
            for(j=n-1;j>i;j--) {
                if(array[j-1]>array[j]) {
                    tmp = array[j-1];
                    array[j-1]=array[j];
                    array[j]=tmp;
                }
            }
        }
    }
    
    int A(int a) {
        int n = 10;
        int array[n],i;
        srand(time(NULL));//随机种子
        for(i=0;i<n;i++) {
            array[i] = rand()%100+1;//1~100内随机数
            printf("%d, ",array[i]);
        }   
        printf("\n");
        bubble_sort(array,n);
        return array[0];
    }
    

    将其编译成so库。操作系统为ubuntu 14.04,gcc版本为4.8.4

    $ gcc -c -fPIC -o shooter.o shooter.c
    $ gcc -shared -o libshooter.so shooter.o
    $ ll
    total 76
    drwx------ 2 linc linc  4096 10月 31 11:46 ./
    drwx------ 7 linc linc  4096 10月 20 20:06 ../
    -rwxrwxr-x 1 linc linc  8251 10月 31 11:46 libshooter.so*
    -rw-rw-r-- 1 linc linc   469 10月 31 11:32 shooter.c
    -rw------- 1 linc linc   137 10月 31 11:22 shooter.h
    

    测试其功能

    新建shooter_tester.c调用此so的方法,验证其功能。

    #include <stdio.h>
    #include "shooter.h"
    
    int main() {
        int result = A(0);
        printf("A result: %d\n",result);
        return 0;
    }
    

    编译运行:

    $ gcc -o shooter_tester shooter_tester.c -lshooter -L.
    $ ./shooter_tester 
    ./shooter_tester: error while loading shared libraries: libshooter.so: cannot open shared object file: No such file or directory

    还是没有找到so文件:

    $ ldd shooter_tester
        linux-vdso.so.1 =>  (0x00007ffea5997000)
        libshooter.so => not found
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f47715bb000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f4771980000)

    解决办法参考网友Vamei(第三个链接):

    $ gcc -o shooter_tester shooter_tester.c -lshooter -L. -Wl,-rpath=.
    $ ./shooter_tester 
    92, 6, 79, 33, 32, 24, 93, 79, 44, 22, 
    A result: 6

    库已建好,等你来用!Shooter!

    参考:
    http://blog.csdn.net/liming0931/article/details/7272696
    http://blog.chinaunix.net/uid-26833883-id-3219335.html
    http://www.cnblogs.com/vamei/archive/2013/04/04/2998850.html



沪ICP备19023445号-2号
友情链接