一.用gcc生成静态库和动态库。
(1)先创建test1目录,保存测试的文件。
mkdir test1
cd test1
(2)用 vim生成3 个文件, hello.c hello.h main.c 。
创建hello.c
vim hello.c
#include <stdio.h>
void hello(const char *name)
{
printf("Hello %s!\n", 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("everyone");
return 0;
}
(3)将hello.c编译成.o文件
gcc -c hello.c
(4)创建静态库并使用
ar -crv libmyhello.a hello.o
gcc main.c libmyhello.a -o hello
(5)gcc创建动态库并使用
创建动态库
gcc -c -fPIC hello.c
gcc -shared -fPIC -o libmyhello.so hello.c
使用动态库
gcc main.c libmyhello.so -o hello
错误:找不到动态库文件 libmyhello.so
由于文件 libmyhello.so 不在目录/usr/lib 中,权限不够,因此要修改权限。移动成功后,使用动态库,则hello程序执行成功。
sudo su
(6)静态库和动态库同名
比较静态库和动态库是否同名,按照以上步骤,重建静态库(.a)和动态库(.so)文件。
运行hello程序后,出现错误,说明gcc先使用动态库
二.用gcc静态库.a与.so库文件的生成与使用
(1)创建test2目录,保存测试的文件。
(2) 用 vim生成4个文件,A1.c 、A2.c、A.h和test.c 。
A1.c
#include <stdio.h>
void print1(int arg){
printf("A1 print arg:%d\n",arg);
}
A2.c
#include <stdio.h>
void print2(char *arg){
printf("A2 printf arg:%s\n", arg);
}
A.h
#ifndef A_H
#define A_H
void print1(int);
void print2(char *);
#endif
test.c
#include <stdlib.h>
#include "A.h"
int main(){
print1(1);
print2("test");
exit(0);
}
(3)生成目标文件A1.o、A2.o
gcc -c A1.c A2.c
(4)生成静态库文件 liba.a
ar crv liba.a a1.o a2.o
(5) 生成.a 库文件,创建可执行程序
gcc -o test test.c libafile.a // 使用.a库文件
./test
(6)共享库.so文件的生成与使用
生成.so库文件
gcc -shared *.o -o libsofile.so //生成共享库.so 文件
使用.so库文件
gcc -o test test.c libsofile.so // 使用.so 库文件
./test
程序出现错误,运行ldd test,检查链接情况
ldd test
无法找到对应的.so文件,则需要将对应so文件拷贝到对应路径
sudo cp libsofile.so /usr/lib
成功运行
三、程序实践
1、静态库.a 文件的生成与使用
(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
#include"x.h"
float x2x(int a,int b)
{
return a*b;
}
x2y.c
#include"x.h"
float x2y(int a,int b)
{
return a/b;
}
main.c
#include<stdio.h>
#include"sub1.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目标文件
gcc -c x2x.c x2y.c
(3)将目标文件生成一个静态库.a 文件
ar crv xy.a x2x.o x2y.o
(4)使用.a 库文件
gcc -o main main.c xy.a
输出计算结果。
2、共享库.so 文件的生成与使用
(1)生成目标.o文件
gcc -c -fpic x2x.c x2y.c
(2)生成共享库.so 文件
gcc -shared *.o -o xy.so
(3)使用.so 库文件
gcc -o main main.c xy.so
运行错误,出现报错。修改权限。
sudo cp -i xy.so /usr/lib
运行成功得到最终结果。
总结:
通过用gcc生成静态库和动态库的练习,基本上能够熟练掌握的生成静态库和动态库。在两种库的比较中,能够明显看出两者的差别。经过多次练习已经能够熟练掌握有关Linux操作系统的大部分指令,掌握了生成静态库.a文件和动态库.os文件,函数调用静态库和动态库的方法。
参考文献:
(46条消息) “用gcc生成静态库和动态库”及“静态库.a与.so库文件的生成与使用”_毛哥的博客的博客-CSDN博客