一、静态库与动态库的初步认识
静态库:
在程序编译时会被连接到目标代码中,程序运行不需要静态库的存在。
动态库:
在程序编译时不会被连接到目标代码中,而是程序运行时载入的。
两者区别:前者是编译连接的,后者是程序运行载入的。
二、库的使用
1.准备代码
hello.h
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif//HELLO_H
hello.c
#include<stdio.h>
void hello(const char *name)
{
printf("Hello %s\n",name);
}
main.c
#include"hello.h"
int main()
{
hello("everyone");
return 0;
}
编译得到.o文件:
2.静态库
创建静态库的工具: ar
静态库文件命名规范:以lib作为前缀,是.a文件
输入指令:ar -crv libmyhello.a hello.o
ls
使用静态库:
gcc main.c libmyhello.a -o hello
./hello
3.动态库
创建动态库
创建动态库的工具:gcc
动态库文件命名规范:以lib作为前缀,是.so文件
我们需要用rm先将原有的静态库删掉
rm libmyhello.a
使用动态库
在这里运行可执行文件hello,会出现错误,将libmyhello.so复制到目录/usr/lib中。由于运行时,是在/usr/lib中找库文件的。
4.静态库与动态库的比较
gcc编译得到.o文件 gcc -c hello.c
创建静态库 ar -crv libmyhello.a hello.o
创建动态库 gcc -shared -fPIC -o libmyhello.so hello.o
使用库生成可执行文件 gcc -o hello main.c -L. -lmyhello
执行可执行文件 ./hello
在执行可执行文件,会报一个错误,