so的封装和使用

背景

在linux平台下,要实现函数的封装,一般采用的是so动态库的形式
实现了函数的封装就意味着实现过程的隐藏
可以实现跨平台和跨语言的使用

实施步骤

生成so动态库

  1. 编写相应的c文件代码,实现函数功能,例如:

    1
    2
    3
    4
    int sum(int a, int b)
    {
    return a + b;
    }
  2. 使用gcc编译时添加-fPIC选项,生成位置无关代码(由于动态库在编译时候无法知道偏移地址),同时添加-shared选项,生成so共享库

    1
    gcc -c test.c -fPIC -o test.o
1
gcc -shared -o libtest.so test.o

注:在linux和unix中的so文件,其扩展名必须是so,文件前缀也必须是lib。

使用so动态库

  1. 编写头文件,声明函数

    1
    2
    3
    4
    5
    6
    #ifndef __SONAME_H
    #define __SONAME_H

    int sum(int a, int b);

    #endif
  2. 在要使用的源文件内包含头文件

    1
    2
    3
    4
    5
    6
    7
    8
    #include <stdio.h>
    #include "soname.h"

    int main()
    {
    printf("sum = %d", sum(1,2));
    return 0;
    }
  3. 编译时候建立连接,gcc链接时添加-L(代表在当前目录下查找so库),-l文件名(此时的文件名不包括前缀和后缀)

    1
    gcc –o test –L. –ltest main.o

修改配置文件使得可以在当前目录查找so库

1
2
3
4
cd 
vi .bash_profile
export LD_LIBRARY_PATH = $LD_LIBRARY_PATH:.
. .bash_profile
Donate comment here