嵌入式第二次作业
文章目录
前言
阅读、理解和学习材料“用gcc生成静态库和动态库.pdf”和“静态库.a与.so库文件的生成与使用.pdf”,在Linux系统(Ubuntu)下如实仿做一遍。
正文
一、hello示例
1.写gedit和编译
先在文本编辑器中编写相关的文本保存到文件中,如下:
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;
}
然后gcc编译生成.o文件
gcc -c hello.c
如图:
2.使用静态库
创建静态库(用ar)
ar -crv libmyhello.a hello.o
如图:
使用静态库
gcc -o hello main.c -L. -lmyhello
gcc main.c libmyhello.a -o hello
gcc -c main.c
gcc -o hello main.c libmyhello.a
验证静态库
rm libmyhello.a
在删掉静态库的情况下,运行可执行文件,发现程序仍旧正常运行,表明静态库跟程序执行没有联系。同时,也表明静态库是在程序编译的时候被连接到代码中的。
3.使用动态库
创建动态库(用gcc)
lib为前缀的so文件
gcc -shared -fPIC -o libmyhello.so hello.o
执行动态库
gcc -o hello main.c -L. -lmyhello 执行后会出错
mv libmyhello.so /usr/lib 可解决(加上sudo)
4.动静态库比较
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
提示error。当静态库和动态库同时存在的时候,程序会优先使用动态库。
二、练习示例
1.准备
先在文本编辑器中编写相关的文本保存到文件中,如下:
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<stdio.h>
#include"A.h"
int main()
{
print1(1);
print2("test");
exit(0);
}
如图:
2.使用静态库
按步骤输入命令后会出现警告
gcc -c A1.c A2.c
ar crv libfile.a A1.o A2.o
gcc -o test test.c libfile.a
将test.c中的exit(0)修改为return 0,方可解决,如下:
3.使用动态库
三、改编作业一
1.准备
先在文本编辑器中编写相关的文本保存到文件中,如下:
sub1.c
float x2x(int a,int b)
{
float c=0;
c=a*b;
return c;
}
sub2.c
float x2y(int a,int b)
{
float c=0;
c=a/b;
return c;
}
sub.h
#ifndef SUB_H
#define SUB_H
float x2x(int a,int b);
float x2y(int a,int b);
#endif
main.c
#include<stdio.h>
#include"sub.h"
void main()
{
int a,b;
printf("Please input the value of a:");
scanf("%d",&a);
printf("Please input the value of b:");
scanf("%d",&b);
printf("a*b=%.2f\n",x2x(a,b));
printf("a/b=%.2f\n",x2y(a,b));
}
如图:
2.静态库
gcc -c sub1.c sub2.c
ar crv libsub.a sub1.o sub2.o
gcc -o main main.c libsub.a
输入后结果正确:
3.动态库
如图:
4.比较
静态库:
动态库:
结论:静态库要比动态库小很多,生成的可执行文件大小也存在较小的差别。
总结
本次作业让我掌握了新的知识,对静态库.a与动态库.so文件的运用。也让我复习了前面学的知识,并且用新知识对上次的作业进行改编,又有了新的理解。