用gcc生成.a静态库与.so动态库

目录

一.gcc生成静态库和动态库

1.创建文件test并使用文本编辑器Vim编程程序hello.h,hello.c和main.c。

2.将hello.c编译成.o文件。

3.由.o文件创建静态库。

 4.在程序中使用静态库。

5.由.o文件创建动态库。

6.在程序中使用动态库。

二.Linux下静态库和动态库的生成和使用

 1.新建文件夹test1并打开,使用vim命令编辑文件

2.静态库.a文件的生成和使用。

3.共享库.so文件的生成和使用

 三.实例使用静动态库

 1.新建文件夹hello并打开,使用vim命令编辑文件

2.静态库.a 文件的生成与使用

 3.共享库.so 文件的生成与使用


一.gcc生成静态库和动态库

1.创建文件test并使用文本编辑器Vim编程程序hello.h,hello.c和main.c。

mkdir test//创建文件夹test
cd test//打开文件夹tes

  

 

按Esc键进入命令模式,输入:wq  然后敲击enter保存退出

 以此类推

main.c

#include "hello.h" 
int main() {
hello("everyone"); 
return 0; }

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

2.将hello.c编译成.o文件。

3.由.o文件创建静态库。

 

 4.在程序中使用静态库。

5.由.o文件创建动态库。

6.在程序中使用动态库。

 

程序执行时出错,找不到动态库文件,要将动态库文件移动到usr/lib目录下,权限不够,使用命令su到管理员再次移动文件,再执行。

先删除.c和.h外的所有文件,再来创建libmyhello.a和libmyhello.so文件。

 当静态库和动态库重名时,gcc命令优先使用动态库。

二.Linux下静态库和动态库的生成和使用

 1.新建文件夹test1并打开,使用vim命令编辑文件

 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);
}

2.静态库.a文件的生成和使用。

3.共享库.so文件的生成和使用

 

 出现错误,可以运行ldd test查看链接情况

移动.so文件位置 

 

 三.实例使用静动态库

 1.新建文件夹hello并打开,使用vim命令编辑文件

 x2x.c

#include<stdio.h>
float f1(int a,int b){
float i;
i=a+b;
printf("This is x2x.c!\n");
return i;
}

x2y.c

#include<stdio.h>
float f2(int a,int b){
float i;
i=a*b;
printf("This is x2x.c!\n");
return i;
}

main.c

#include<stdio.h>
#include"x.h"
int main(){
        int a=2,b=3;
        float m,n;
        m=f1(a,b);
        printf("%f\n",m);
        n=f2(a,b);
        printf("%f\n",n);
        return 0;
}

x.h

#ifndef x_H 
#define x_H
float f1(int,int);
float f2(int,int);
#endif
      

2.静态库.a 文件的生成与使用

生成目标文件并用ls命令查看文件生成情况

生成静态库.a 文件

使用.a 库文件,创建可执行程序并运行程序

 3.共享库.so 文件的生成与使用

执行但是会报错

解决方法并再次执行

总结;通过这一次实验我掌握了GCC生成静态库和动态库的命令,当动态库和静态库重名时会优先使用动态库 

 

 参考文献:

(3条消息) gcc生成静态库.a和动态库.so_Harriet的博客-CSDN博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值