静态库和动态库
简介
我们所说的程序编译往往包含以下四个步骤:
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