动态库简介

来源:互联网 发布:工业机器人控制软件 编辑:程序博客网 时间:2024/05/01 23:42

一、 动态库概述

1.  库文件搜索路径顺序

  • 编译目标代码时指定的动态库搜索路径“-W1, -rpath”
  • 环境变量LD_LIBRARY_PATH
  • 配置文件/etc/ld.so.conf(ldconfig)
  • /lib
  • /usr/lib

2. 让linux加载当前目录的动态库的方法

方法一:临时修改,logout之后失效
export LD_LIBRARY_PATH=./
方法二:影响所有账号,修改文件/etc/profile,添加如下信息
LD_LIBRARY_PATH=./exprot LD_LIBRARY_PATH

方法三:影响所有账号,修改文件/etc/profile,添加如下信
LD_LIBRARY_PATH=./exprot LD_LIBRARY_PATH

二、 动态库示例

1. 编译并生产动态库

1. 动态库接口文件get_max_value.hint getMaxValue(const int iFirstValue, const iSecondValue)#ifndef _GETMAXLAULE_#define _GETMAXLAULE_int getMaxValue(const int iFirstValue, const iSecondValue);#endif 2. 动态库实现文件get_max_value.c#include "get_max_value.h"/************************************ * 函数名称:getMaxValue * 功能描述:获取两个参数中的最大值 * 输入参数:iFirstValue, iSecondValue * 输出参数:无 * 返回值:  两个参数中的最大值 * 其它说明: * 修改日期: ************************************/int getMaxValue(const int iFirstValue, const int iSecondValue){    if (iFirstValue > iSecondValue)        return iFirstValue;    else        return iSecondValue;} 3. 编译动态库gcc get_max_value.c -fPIC -shared -o libmaxvalue.so(动态库需要以lib开头,so结尾)

2. 运用动态库

1. 运用动态库的文件:test_max_value.c#include "get_max_value.h"#include <string.h>#include <stdio.h> int main(void){    int a = 12, b =6;    int tmp = 0;     tmp = getMaxValue(a, b);    printf("tmp = %d\n", tmp);     return 0;} 2. 编译文件[root@f8s dynamic_lib]# gcc test_max_value.c -L . -l maxvalue -o test_max_value[root@f8s dynamic_lib]# lsget_max_value.c  get_max_value.h  libmaxvalue.so  test_max_value  test_max_value.c 3. 执行结果[root@f8s dynamic_lib]# ./test_max_value tmp = 12

三、 常见疑难解答

1. 问题现象[root@f8s dynamic_lib]# ./test_max_value ./test_max_value: error while loading shared libraries: libmaxvalue.so: cannot open shared object file: No such file or directory2. 问题原因:运行时,找不到共享库(注意-L选项指定的是编译时搜索的库路径,而不是运行时)3. 问题解决方法一:执行export LD_LIBRARY_PATH=./方法二:编译目标代码时指定动态搜索路径: -Wl,-rpath,./[root@f8s dynamic_lib]# gcc test_max_value.c -L. -l maxvalue -Wl,-rpath,./ -o test_max_value


原创粉丝点击