目录
一、用gcc生成静态库和动态库
1.以hello world为例
(1)创建hello.c,hello.h,main.c程序
(2)再生成.o文件
(3)生成.a静态库文件
(4)在程序中使用静态库
(5)创建.so动态库文件
(6)在程序中使用动态库
二、实例演示
1.程序编写
2.生成.a静态库文件
3、生成 .so 动态库文件
4.静态库与动态库文件大小对比
三、总结
四、参考文献
一、用gcc生成静态库和动态库
1.以hello world为例
(1)创建hello.c,hello.h,main.c程序
(1)创建hello.c,hello.h,main.c程序
先在终端中输入代码
mkdir hello
cd hello
创建hello文件夹
然后使用gedit生成hello.c,hello.h,main.c三个文件,三个文件源代码如下
hello.c
#includevoid hello(const char *name) { printf("Hello %sn", name); }
hello.h
#ifndef HELLO_H #define HELLO_H void hello(const char *name); #endif //HELLO_H
main.c
#include "hello.h"
int main()
{
hello("world");
return 0;
}
(2)再生成.o文件
利用gcc -c hello.c生成hello.o的文件、
(3)生成.a静态库文件
静态库文件名的命名规范是以 lib 为前缀,紧接着跟静态库名,扩展名为.a。例如:我们将 创建的静态库名为 myhello,则静态库文件名就是 libmyhello.a。在创建和使用静态库时, 需要注意这点。创建静态库用 ar 命令。在系统提示符下键入以下命令将创建静态库文件 libmyhello.a。
ar -crv libmyhello.a hello.o
(4)在程序中使用静态库
输入代码
gcc main.c libmyhello.a -o hello
再输入./hello输出程序结果
(5)创建.so动态库文件
在终端输入创建一个动态库文件
gcc -shared -ffPIC -o libmyhello.so hello.o
(6)在程序中使用动态库
在终端输入进行使用
gcc main.c libmyhello.so -o hello
输入之后再./hello运行会发生错误
输入sudo su 输入密码之后进入root模式再输入./hello进行程序运行
当静态库和动态库同名时,gcc 命令将优先使用动态库
二、实例演示
过程同上述一致就不过多的叙述
1.程序编写
编写4个c 语言文件程序代码如下
main.c
#include"sub1.h"
#include"sub2.h"
int main()
{
int x=2,y=3;
printf("%.5fn",x2x(x,y));
printf("%fn",x2y(x,y));
return 0;
}
sub1.c
#include"sub1.h"
float x2x(int a,int b)
{
float c;
c=(float)a/b;
return c;
}
sub1.h
#ifndef __SUB1_H
#define __SUB1_H
#include
float x2x(int a,int b);
#endif
sub2.c
#include"sub2.h"
float x2y(int a,int b)
{
float d;
d=a+b;
return d;
}
sub2.h
#ifndef __SUB2_H
#define __SUB2_H
#include
float x2y(int a,int b);
#endif
2.生成.a静态库文件
3、生成 .so 动态库文件
4.静态库与动态库文件大小对比
三、总结
通过上述的两个例子,能够熟悉了解动态和静态库,虽然在完成整个的操作时遇到了一些大大小小的问题,但最终还是通过参考不少大佬的文章得以完成。
四、参考文献
https://blog.csdn.net/pink_lemon/article/details/120613458
https://blog.csdn.net/qq_43279579/article/details/109026927



