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
错误的原因,下一节,讲解。