正文开始!
安装C语言静态库
yum install -y glibc -static
首先我们库里面是不需要包含main函数的!
链接:就是把所有的.o链接形成一个可执行程序!!!
如果我把我的所有的.o给别人,别人能链接使用吗??—> 当然是可以的!
测试程序
/mymath.h//
#pragma once
#include
#include
//[from,to]-->累加-->result--->return
extern int addToVal(int from,int to);/mymath.c//
#include"mymath.h"
int addToVal(int from,int to)
{assert(from<=to);int result=0;for(int i=from;i<=to;i++){result+=i;}return result;
}/myprint.h//
#pragma once
#include
#include
extern void Print(const char* msg); /myprint.c//
#include"myprint.h"
void Print(const char* msg)
{printf("%s : %lld\n",msg,(long long)time(NULL));
}
命令
ar -rc [文件]
(ar是gnu的归档工具,rc表示(replace and create))
libmymath.a:mymath.o myprint.oar -rc libmymath.a mymath.o myprint.o
mymath.o:mymath.cgcc -c mymath.c -o mymath.o -std=c99
myprint.o:myprint.cgcc -c myprint.c -o myprint.o -std=c99
.PHONY:clean
clean:rm -f *.o *.a
问题:我们在用库的时候需要什么东西呢??
答:库文件和头文件!!—>就可以给别人使用了
命令
.PHONY:static
static:mkdir -p lib-static/lib;\mkdir -p lib-static/include;\cp *.a lib-static/lib;\cp *.h lib-static/include
libmymath.so:mymath.o myprint.ogcc -shared -o libmath.so mymath.o myprint.o
mymath.o:mymath.cgcc -fPIC -c mymath.c -o mymath.o -std=c99
myprint.o:myprint.cgcc -fPIC -c myprint.c -o myprint.o -std=c99.PHONY:clean
clean:rm -rf *.o *.so
.PHONY:dyl
dyl:mkdir -p lib-dyl/lib;\mkdir -p lib-dyl/include;\cp *.so lib-dyl/lib;\cp *.h lib-dyl/include
#include"mymath.h"
#include"myprint.h"int main()
{int start=0;int end=100;int result=addToVal(start,end);printf("%d\n",result);Print("hello world");return 0;
}
首先我们先来回顾C语言头文件的搜索路径: “” <>
谁在头文件呢???—>编译器---->进程
ls /usr/include/
ls /lib64/
将自己的头文件和库文件,拷贝到系统路径下即可!!!(库的安装)
sudo cp lib-static/include/* /usr/include/
sudo cp lib-static/lib/* /usr/lib64/
其实我们之前没有用过任何第三方库!
gcc -l(指明我要链接的第三方库的名称)
但是不推荐这种做法,因为这种做法会污染系统的头文件和库文件!
gcc mytest.c -o mytest -I ./lib-static/include/
虽然有错误,但并不是说头文件找不到了,现在还需要我们链接库文件!
gcc mytest.c -o mytest -I ./lib-static/include/ -L ./lib-static/lib/ -lmymath
如果安装到系统就没有这么麻烦了。
sudo rm /usr/include/mymath.h
sudo rm /usr/include/myprint.h
sudo rm /lib64/libmymath.a
第一种方法和静态库的使用一模一样:将自己的头文件和库文件,拷贝到系统路径下即可!!!
这里就不做演示了!
第二种指定路径包含头文件和库文件
但是我们运行程序去报错了!!
查看我们程序所依赖的库
ldd mytest
问题来了:编译的时候gcc所带的-I,-L,-l选项是给谁带的? ---->gcc
所以形成可执行程序后,与编译器gcc就没有任何关系了。
所以./mytest运行进程后,并没有告诉进程这个库链接在哪里!!
根据上面的问题,进程找不到对应的动态库!
那么如何解决找不到动态库的问题呢??
想办法让进城找到动态库即可!
通过导入环境变量的方式
echo LDLIBRARYPATHexportLDLIBRARYPATH=LD_LIBRARY_PATH export LD_LIBRARY_PATH=LDLIBRARYPATHexportLDLIBRARYPATH=LD_LIBRARY_PATH:[绝对路径]
这个解决办法重启Xshell就不可以了,因为Xshell默认重启后会还原环境变量!
系统配置文件来做
[root@localhost linux]# cat /etc/ld.so.conf.d/bit.conf
/root/tools/linux
[root@localhost linux]# ldconfig
查看还是发现没有我们需要链接的动态库
sudo ldconfig
现在我们就能找到动态库并且运行了
这个解决方法Xshell关闭后也不受影响!!
其他方式
sudo ln -s /home/hulu/2022_10_27/mklib/test/lib-dyl/lib/libmath.so /lib64/libmath.so
该方法就是在系统库创建了一个软链接!
(本章完)