编译静态库,在Mac系统下:
//
// hello1.h
//
#include "hello1.h"
void myPrint1(int i)
{
int j;
for(j = 0; j < i; j ++)
{
printf("%d * %d = %d\n", j, j, j * j);
}
}
//
// hello1.c
//
#ifndef HELLO1_H_INCLUDED
#define HELLO1_H_INCLUDED
#include <stdio.h>
void myPrint1(int i);
#endif // HELLO1_H_INCLUDED
//
// hello2.h
//
#ifndef HELLO2_H_INCLUDED
#define HELLO2_H_INCLUDED
#include <stdio.h>
void myPrint2(char *arr);
#endif // HELLO2_H_INCLUDED
//
// hello2.c
//
#include "hello2.h"
void myPrint2(char *arr)
{
char c;
int i = 0;
while((c = arr[i++])!= '\0')
{
printf("%d****%c\n", i, c);
}
}
//
// main.c
//
#include <stdio.h>
#include <stdlib.h>
#include "hello1.h"
#include "hello2.h"
int main()
{
int i = 100;
char *arr = "This is Kity's home";
myPrint1(i);
myPrint2(arr);
return 0;
}
可以看到main.c要用到hello1.c中的myPrint1函数和hello2.c中的myPrint2函数。所以可以把这两个函数组合为库,以供更多的程序作为组件来调用。
方法一:将hello1.c和hello2.c编译成静态链接库.a
// 将hello1.c和hello2.c分别编译为hello1.o和hello2.o,其中-c选项意为只编译不链接。
[root@localhost main5]#gcc -c hello1.c hello2.c
//将hello1.o和hello2.o组合为libhello.a这个静态链接库
[root@localhost main5]#ar -r libhello.a hello1.o hello2.o
//将hello.c编译为可执行程序hello.exe
[root@localhost main5]#gcc -o hello hello.c -libhello.a
方法二:将hello1.o和hello2.o组合成动态链接库.so
// 将hello1.c和hello2.c编译成hello1.o和hello2.o,-c意为只编译不链接,-fpic意为位置独立代码,指示编译程序生成的代码要适合共享库的内容这样的代码能够根据载入内存的位置计算内部地址。
[root@localhost main5]#gcc -c -fpic hello1.c hello2.c
// 将hello1.o和hello2.o组合为shared object,即动态链接库
[root@localhost main5]#gcc -shared hello1.o hello2.o -o hello.so
//将main.c编译链接为hello.exe的可执行程序,这个过程用到了动态链接库hello.so
[root@localhost main5]#gcc -o hello hello.c hello.so