so的封装和使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cj5785/article/details/88983694

背景

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

实施步骤

生成so动态库

  1. 编写相应的c文件代码,实现函数功能,例如:
int sum(int a, int b)
{
    return a + b;
}
  1. 使用gcc编译时添加-fPIC选项,生成位置无关代码(由于动态库在编译时候无法知道偏移地址),同时添加-shared选项,生成so共享库
gcc -c test.c -fPIC -o test.o
gcc -shared -o libtest.so test.o

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

使用so动态库

  1. 编写头文件,声明函数
#ifndef __SONAME_H
#define __SONAME_H

int sum(int a, int b);

#endif
  1. 在要使用的源文件内包含头文件
#include <stdio.h>
#include "soname.h"

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

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

cd 
vi .bash_profile
export LD_LIBRARY_PATH = $LD_LIBRARY_PATH:.
. .bash_profile

猜你喜欢

转载自blog.csdn.net/cj5785/article/details/88983694