在linux下打造libxxx.so 动态库

在linux下制作libxxx.so 动态库

在linux下面动态库的使用是非常常用的,也是非常实用的。

步骤一:

创建一个.h头文件 ,头文件中声明动态库中的函数

#ifndef _TEST_H_
#define _TEST_H_

#ifdef __cplusplus       /*c c++ 混合编程*/
extern "C" {
#endif                   <span style="font-family: Arial, Helvetica, sans-serif;">/*c c++ 混合编程*/</span>


int max(int a, int b);
int add(int a, int b);

#ifdef __cplusplus        <span style="font-family: Arial, Helvetica, sans-serif;">/*c c++ 混合编程*/</span>

}
#endif                   <span style="font-family: Arial, Helvetica, sans-serif;">/*c c++ 混合编程*/</span>



#endif


步骤二

创建.c文件实现头文件中的函数

int max(int a, int b){
        if (a > b){
                return a;
        }else{
                return b;
        }
}

int add(int a, int b){
        return a+b;
}

步骤三:
<span style="white-space:pre">	</span>编写makefile文件 ,在编译命令中添加 -shared 参数
<span style="white-space:pre">	</span>在链接命令中添加 -fPIC 参数
<span style="white-space:pre">	</span><pre style="line-height: 28px; white-space: pre-wrap; color: rgb(105, 105, 105); background-color: rgb(255, 255, 255);"><pre style="white-space: pre-wrap;"><span style="font-size:14px;"><span style="color: rgb(255, 0, 0);"><span style="white-space:pre">	</span>-shared:</span> 该选项指定生成动态连接库;
<span style="color: rgb(255, 0, 0);">        -fPIC:</span>表示编译为<span style="color: rgb(255, 0, 0);">位置独立(地址无关)</span>的代码,不用此选项的话,编译后的代码是位置相关的,所以动态载入时,是代码拷贝的方式</span>

        -L:指定链接库的路径,-L. 表示要连接的库在当前目录中
       -ltest:指定链接库的名称为test,编译器查找动态连接库时有隐含的命名规则,即在给出的名字前面加上lib,后面加上.so来确定库的名称
       -Wl,-rpath: 记录以来so文件的路径信息。
       LD_LIBRARY_PATH:这个环境变量指示动态连接器可以装载动态库的路径。
      当然如果有root权限的话,可以修改/etc/ld.so.conf文件,然后调用 /sbin/ldconfig来达到同样的目的,
      不过如果没有root权限,那么只能采用修改LD_LIBRARY_PATH环境变量的方法了。
.SUFFIXES:.c.o
CC = gcc
SRC = test.c
OBJK = $(SRC:.c=.o)
EXEC = libtest.so
start: $(OBJK)
        $(CC) -shared -o $(EXEC) $(OBJK)
        @echo ---------------ok-------------------
.c.o:
        $(CC) -Wall -fPIC -g -o $@ -c $< 
clean:
        rm -f $(OBJK)
        rm -f $(EXEC)
        rm -f core.*

使用该动态库
	gcc -L/动态库所在路径 使用该动态库.c文件 -lXXX 动态库名