加入收藏 | 设为首页 | 会员中心 | 我要投稿 百客网 - 百科网 (https://www.baikewang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

库的制作---函数库

发布时间:2023-01-14 14:55:37 所属栏目:Linux 来源:
导读:  1>静态库

  静态库对函数库的链接是放在编译时期(compile time)完成的。

  gcc的四步骤:预处理---编译---汇编---链接

  .i .s .o a.out

  优点:程序在运行时与函数库再无瓜葛,移植
  1>静态库
 
  静态库对函数库的链接是放在编译时期(compile time)完成的。
 
  gcc的四步骤:预处理---编译---汇编---链接
 
  .i .s .o a.out
 
  优点:程序在运行时与函数库再无瓜葛,移植方便
 
  缺点:浪费空间和资源,因为所有相关的对象文件(object file)与牵涉到的函数 库(library)被链接合成一个可执行文件(executable file)。
 
  1>如何创建静态库
 
  1>创建一个库源文件:mylib.c
 
  int myplus(int a,int b)
 
  {
 
  return a + b;
 
  }
 
  int myusb(int a,int b)
 
  {
 
  return a - b;
 
  }
 
  2>将库源文件编译成.o的工程目标文件
 
  gcc -c mylib.c -o mylib.o
 
  -c:gcc编译对文件进行编译并汇编linux动态库,但不进行链接
 
  3>将.o文件制作成静态库文件 //静态库命名规则:必须 lib库名.a
 
  。、
 
  4>编写一个测试代码:test.c
 
  #include
 
  #include "mylib.h"
 
  int main(){
 
  int a,b;
 
  printf("请输入a和b:");
 
  scanf("%d %d",&a,&b);
 
  printf("%d + %d =%d\n",a,b,myplus(a,b));
 
  printf("%d - %d =%d\n",a,b,myusb(a,b));
 
  return 0;
 
  }
 
  5>编译test.c的同时链接制作的静态库
 
  gcc -Wall -o test test.c -L. -lmylib
 
  -Wall 检查编译
 
  -L. 库的路径
 
  -lmylib 库名
 
  6>运行
 
  ./test
 
  1 + 2 =3
 
  1 - 2 =-1
 
  2>动态库(共享库)
 
  1>动态库的特点
 
  1>动态库把对一些库函数的链接载入推迟到程序运行的时期(runtime)。
 
  2>可以实现进程之间的资源共享。
 
  3>将一些程序升级变得简单。
 
  4>甚至可以真正做到链接载入完全由程序员在程序代码中控制。
 
  2>如何创建动态库
 
  1>创建一个库源文件:mylib.c
 
  int myplus(int a,int b)
 
  {
 
  return a + b;
 
  }
 
  int myusb(int a,int b)
 
  {
 
  return a - b;
 
  }
 
  2>将库源文件编译成.o的工程目标文件
 
  gcc -fPIC -Wall -c mylib.c
 
  //创建一个与地址无关的编译程序
 
  3>将.o文件制作成动态库文件
 
  gcc -shared -fPIC -o libmylib.so mylib.o
 
  4>编写一个测试代码:test.c
 
  #include
 
  #include "mylib.h"
 
  int main(){
 
  int a,b;
 
  printf("请输入a和b:");
 
  scanf("%d %d",&a,&b);
 
  printf("%d + %d =%d\n",a,b,myplus(a,b));
 
  printf("%d - %d =%d\n",a,b,myusb(a,b));
 
  return 0;
 
  }
 
  5>编译test.c的同时链接制作的动态库
 
  gcc -Wall -o test test.c -L. -lmylib
 
  6>发现运行不了test
 
  ./test: error while loading shared libraries: libmylib.so: cannot open shared object file: No such file or directory
 
  将动态库加载入系统中-----如何让系统找到动态库?
 
  三个方法
 
  方法一:
 
  直接将动态库文件放入/lib 或/usr/lib 中
 
  方法二:
 
  将动态库所在路径加入配置文件中
 
  配置文件:/etc/ld.so.conf
 
  打开文件:sudo vim /etc/ld.so.conf
 
  添加下面一行
 
  /home/farsight/shared/IO/day4/DT_lib
 
  wq退出后执行命令
 
  sudo ldconfig
 
  方法三:添加环境变量
 
  将动态库所在路径,加入到环境变量中:LD_LIBRARY_PATH
 
  在命令行中执行命令:
 
  export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/farsight/shared/IO/day4/DT_lib
 
  7>运行
 
  ./test
 
  升级一下动态库
 
  1>修改库源文件
 
  #include
 
  int myplus(int a,int b)
 
  {
 
  printf("holy\n");
 
  return a + b;
 
  }
 
  int myusb(int a,int b)
 
  {
 
  printf("shxt\n");
 
  return a - b;
 
  }
 
  2>重新制作动态库
 
  gcc -fPIC -Wall -c mylib.c
 
  gcc -shared -fPIC -o libmylib.so mylib.o
 
  3>再次运行test
 
  15
 
  holy
 
  14 + 15 =29
 
  shxt
 
  14 - 15 =-1
 

(编辑:百客网 - 百科网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!