linux 下静态库的创建及使用

1.创建静态库

[xpan@localhost 2.5.2]$ ls

libhello.c libhello.h usehello.c

[xpan@localhost 2.5.2]$ cat libhello.h

#ifndef _libhello_H_

#define _libhello_H_

void print_hello(void);

#endif /*_libhello_H_*/

[xpan@localhost 2.5.2]$ cat libhello.c

#include<stdio.h>

void print_hello(void)

{

printf("hello world ,this is library\n");

}

[xpan@localhost 2.5.2]$ gcc -c libhello.c

[xpan@localhost 2.5.2]$ ls libhello.o

libhello.o

[xpan@localhost 2.5.2]$ ar rc libhello.a libhello.o

参数:

r: 把目标文件包含在库中,替换任何已经在档案中存在的同名目标文件;

c: 如果目标文件不存在,则默认创建该库;

s: 维护映射符号名到目标文件的表格;

[xpan@localhost 2.5.2]$ ls libhello.a

libhello.a

[xpan@localhost 2.5.2]$ file libhello.a

libhello.a: current ar archive

2.使用静态库

[xpan@localhost 2.5.2]$ cat usehello.c

#include "libhello.h"

/*hello*/

int main(void)

{

print_hello();

return 0;

}

[xpan@localhost 2.5.2]$ gcc -o usehello_static usehello.c libhello.a

[xpan@localhost 2.5.2]$ ./usehello_static

hello world ,this is library

[xpan@localhost 2.5.2]$