gcc 编译静态链接库

来源:互联网 发布:传奇数据库修改 编辑:程序博客网 时间:2024/05/17 04:48
静态链接库(static library)是目标文件(.o文件或.obj文件)的集合,后缀为.a

在编译使用时,静态库会被拷贝到可执行文件中,所以最终生成的可执行文件不依赖于静态库。但这也使得可执行文件庞大,加载速度慢的问题。另外,一旦修改,就必须重新编译,不能想共享库那样灵活的升级。

本文对gcc编辑静态链接库演示一个示例,供参考,好记星不如烂笔头。


1. 编写代码

编写hello.h头文件, 包含print_hello()函数


#ifndef HELLO_H#define HELLO_Hvoid print_hello();#endif
编写hello.c源文件, 包含print_hello函数的实现
#include "hello.h"#include <stdio.h>int main(int argc,char *argv[]){    printf("hello world!");}

2. 编译

编译命令(centos5+gcc4.1.2)

[test@hadoop hello]$ gcc -c hello.c  #将源文件编译为目标文件[test@hadoop hello]$ lshello.c  hello.h  hello.o[test@hadoop hello]$ ar crs libhello.a hello.o #使用ar 将目标文件打包成为.a静态链接库[test@hadoop hello]$ lshello.c  hello.h  hello.o  libhello.a

3. 使用静态库

*******************main.c***************

#include "hello.h"int main(int argc,char *argv[]){    printf_hello();}

编译执行
[test@hadoop hello]$ lshello.c  hello.h  libhello.a  main.c[test@hadoop hello]$ gcc main.c -o main -L. -lhello -I. #在使用静态链接库时, 使用-l指定链接库名称[test@hadoop hello]$ ./mainhello world!
-lhello: 链接libhello.so 或者libhello.a库文件, 其中共享库文件优先. 如果同时存在静态库和共享库,可以使用-static强制使用静态库。
或者直接指定静态库libhello.a
[test@hadoop hello]$ gcc main.c -o main libhello.a


原创粉丝点击