我们要知道,别人给我们.o和.h文件的时候,我们就可以用别人写好的库了。
/mymath.h/
#pragma once
#include
extern int MyAdd(int a, int b);
/mymath.c/
#include"mymath.h"
int MyAdd(int a, int b)
{
return a+b;
}
/myprint.h/
#pragma once
#include
#include
extern void MyPrint(const char* str);
/myprint.c/
#include"myprint.h"
void MyPrint(const char* str)
{
printf("%s[%d]\n", str, (int)time(NULL));
}
///main.c
#include "myprint.h"
#include "mymath.h"
int main()
{
MyPrint("hello world");
int res = MyAdd(1,100);
printf("res: %d\n", res);
return 0;
}
指令:
gcc -c mymath.c -o mymath.o
gcc -c myprint.c -o myprint.o
ar -rc libhello.a mymath.o myprint.o
生成之后,我们要通过目录分开.h和库文件,为调用静态库作准备。
指令
mkdir -p hello/lib
mkdir -p hello/include
cp -rf *.h hello/include
cp -rf *.a hello/lib

完成后如上图。
我们知道我们用软件,需要下载;那我们使用别人的静态库也需要下载;而这里的下载就是把hello路径下的所以东西通过cp指令拷贝的我们使用者(用户)的路径下。

我们gcc后出现下图情况

这很正常,因为我们写的库属于第三方库。

结果展示:

头文件gcc默认搜索路径
/usr/include

库文件gcc默认搜索路径
/usr/lib64 or /lib64

我们把自己的库和头文件拷贝到这个路径下,我们就可以正常使用了,最好不要作,容易造成库污染。