静态库和动态库使用(1)

静态库和动态库

简介

​ 我们所说的程序编译往往包含以下四个步骤:

预编译
编译
汇编
链接

1、预编译

​ 系统针对字符#开头的命令,主要包括头文件引用、宏定义等,对原始的程序进行替换,得到修改之后的程序,通常以.i结尾。

2、编译

​ 编译器将*.i文件翻译成汇编语言程序,以.s结尾。

3、汇编

​ 汇编器将*.s文件翻译成机器语言,即二进制指令,以.o结尾

4、链接

​ 链接器(ld)将合并目标代码,生成可执行文件。

​ 工程中,通常由一些代码会被反复利用,我们可将这些代码编译成库的形式来减少重复劳动。

静态库

​ 由上可知,通过在链接阶段对多个目标代码进行链接,得到可执行文件,故可将事先编译好的目标代码库(静态库)在此阶段加入工程。

​ 以下以简单的hello.c和和sum.c为例,介绍静态库的使用方法。

hello.c
//hello.h
#ifndef _HELLO_H_
#define _HELLO_H_

#include <stdio.h>

extern void helloWorld();

#endif

//hello.c
#include "hello.c"

void helloWorld()
{
    printf("hello world!\n");
    
}
intSwap.c
//intSwap.h
#ifndef _INTSWAP_H_
#define _INTSWAP_H_

#include <stdio.h>

extern void intSwap(int *a, int *b);

#endif 

//intSwap.c
#include "intSwap.h"

void intSwap(int *a, int *b)
{
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;
}
main.c
//main.c
#include <stdio.h>
#include "hello.h"
#include "intSwap.h"

int main()
{
	int x = 10;
	int y = 20;
	printf("x = %d, y = %d\n", x, y);
	helloWorld();
	intSwap(&x, &y);
	printf("x = %d, y = %d\n", x, y);
}

运行结果

$ gcc hello.c -o hello.o -c
$ gcc intSwap.c -o intSwap.o -c
$ ar -crv libmyfunc.a intSwap.o hello.o
r - intSwap.o
r - hello.o
$ gcc -o main main.c -static -L . -l myfunc
$ ./main 
x = 10, y = 20
hello world!
x = 20, y = 10
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值