文章目录
一、简单使用gcc生成静态库和动态库
函数库分为静态库和动态库。
静态库
在程序编译时会被连接到目标代码中,程序运行是则不需要静态库的存在。
动态库
在程序编译时不会被连接到目标代码中,而是程序运行时载入的。
两者区别:前者是编译连接的,后者是程序运行载入的。
1、使用gcc生成静态库
1、创建一个文件目录text1
2、在目录下创建三个文件hello.c main.c 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;
}
hello.h
#ifndef HELLO_H
#define HELLO_H
void hello(const char *name);
#endif //HELLO_H
3、 gcc编译hello.c得到.o文件
gcc -c hello.c
2、静态库的使用
1、创建静态库
创建静态库的工具:ar
静态库文件命名规范:以lib作为前缀,是.a文件
ar -crv libmyhello.a hello.o
2、程序中使用静态库
第一种方法
gcc -o hello main.c -L. -lmyhello
第二种方法
gcc main.c libmyhello.a -o hello
第三种方法
先生成main.o文件
gcc -c hello.c
gcc -o hello main.c libmyhello.a
2、使用gcc生成动态库
1、 创建动态库
gcc -c -fPIC hello.c
gcc -shared -fPIC -o libmyhello.so hello.c
2、在程序中执行动态库
gcc -o hello main.c -L. -lmyhello或gcc main.c libmyhello.so -o hello
错误:找不到动态库文件 libmyhello.so
问题的解决方法:将libmyhello.so复制到目录/usr/lib中。由于运行时,是在/usr/lib中找库文件的。
mv libmyhello.so /usr/lib
二、对上次x2x的程序代码,生成静态库和动态库进行改编
1、创建文件编写代码
1、利用vim指令创建创建四个文件分别为x.h、x2x.c、x2y.c、main.c
x.h
#ifndef HELLO_H
#define HELLO_H
float x2x(int a,int b);
float x2y(int a,int b);
#endif //HELLO_H
x2x.c
float x2x(int a,int b)
{
return a*b;
}
x2y.c
float x2y(int a,int b)
{
return a/b;
}
main.c
#include<stdio.h>
#include"x.h"
int main()
int a=2,b=5; //定义a、b为整数型变量
printf("%f\n",x2x(a,b)); //以小数形式输出函数x2x返回值
printf("%f\n",x2y(a,b)); //以小数形式输出函数x2y返回值
return 0;
}
2、用gcc .c文件编译成.o目标文件
2、静态库的生成与使用
1、将目标文件生成一个静态库.a 文件
2、使用静态库文件
3、动态库的生成与使用
1、生成目标.o文件
gcc -c -fpic x2x.c x2y.c
2、生成共享库.so 文件
gcc -o main main.c xy.so
3、使用动态库文件
若运行错误,出现报错,注意修改权限。
sudo cp -i xy.so /usr/lib
3、静态库与动态库的生成文件的比较
静态库
动态库
通过比较发现静态库要比动态库要小很多,生成的可执行文件大小也存在较小的差别。