Linux系统编程 29 动态库制作 -演示

Linux系统编程 29 动态库制作 -演示

学习笔记

动态库制作及使用:
  1.将.c文件生成.o(与位置无关代码 -fPIC)
  
   gcc -c add.c -o add.o -fPIC
   
  2.使用gcc -shared 制作动态库
    gcc -shared  -o lib库名.so add.p sub.o div1.od
    
  3.编译可执行程序时,指定所使用的动态库 -L -l
  -l 用来指定库名
  -L 用来指定动态库的路径
  
  注意使用动态lib库的时候,lib前缀和.o都要去除
  lib***.so 动态库文件
  gcc ***.c -l*** -L  动态库路径   -I 头文件路径  -o file.out
  4. 运行可执行文件
  
  
 
生成和位置无关代码的目标文件
  
  $cd ../dynaticlib/
$ls
inc  lib  resource  test.c  test.out
$pwd
/home/ubuntu/code/test/dynaticlib
$ls
inc  lib  resource  test.c  test.out
$cd resource
$ls
add.c  add.o  div1.c  div1.o  sub.c  sub.o
$rm add.o div1.o sub.o
$ls
add.c  div1.c  sub.c
$gcc  -c add.c -o add.o -fPIC
$gcc -c sub.c -o sub.o -fPIC
$gcc -c div1.c -o div1.o -fPIC
$LS
The program 'LS' is currently not installed. You can install it by typing:
sudo apt-get install sl
$ls
add.c  add.o  div1.c  div1.o  sub.c  sub.o
$

  
  
 制作动态库
 
  
  $ls
add.c  add.o  div1.c  div1.o  sub.c  sub.o
$^C
$gcc -shared libmymath.so add.o sub.o div1.o
gcc: error: libmymath.so: No such file or directory
$gcc -shared -o libmymath.so add.o sub.o div1.o
$ls
add.c  add.o  div1.c  div1.o  libmymath.so  sub.c  sub.o
$file libmymath.so 
libmymath.so: ELF 64-bit LSB  shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=deef0efc92585880f6aa70351be3d27773c27dd6, not stripped
$cd ../

  

生成可执行文件

$cd inc
$
$ls
mymath.h
$vi mymath.h 
$cd ../
$ls
inc  lib  resource  test.c  test.out
$gcc test.c -l libmymath.so  -L ./resource/ -o testdy.out  
test.c:2:20: fatal error: mymath.h: No such file or directory
 #include "mymath.h"
                    ^
compilation terminated.
$gcc test.c -l libmymath.so  -L ./resource/ -o -I ./inc/  testdy.out   //-o 后面没有接输出的文件名
gcc: error: testdy.out: No such file or directory
$gcc test.c -l libmymath.so  -L ./resource/ -I./inc  -o  testdy.out    //注意使用动态lib库的时候,lib前缀和.o都要去除
/usr/bin/ld: cannot find -llibmymath.so
collect2: error: ld returned 1 exit status
$gcc test.c -llibmymath.so  -L ./resource/ -I./inc  -o  testdy.out  
/usr/bin/ld: cannot find -llibmymath.so
collect2: error: ld returned 1 exit status
$gcc test.c -l mymath  -L ./resource/ -I./inc  -o  testdy.out  
$

执行可执行文件
$ls
inc  lib  resource  test.c  testdy.out  test.out
$./testdy.out 
./testdy.out: error while loading shared libraries: libmymath.so: cannot open shared object file: No such file or directory

错误的原因,下一节,讲解。
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值