linux 静态函数库在编译时试一起编译进程序里的.静态库是libXX.a命名的。
下面是学习中一个静态库的编写学习;
1.在我编写测试的程序中包含如下几个文件:main.c test1.c test2.c mytest.h
其中main.c 为主测试程序, test1.c 和test2.c 分别为包含两个测试函数的文件,mytest.h 为两个测试文件函数声明,具体内容见下:
/*test1.c*/
#include<stdlib.h>
#include<stdio.h>
void test1()
{
printf("test1 is done\n");
}
/*test2.c*/
#include<stdlib.h>
#include<stdio.h>
void test2()
{
printf("test2 is done\n");
}
/*mytest.h*/
#ifndef MY_LIB
#define MY_LIB
void test1()
void test2();
#endif
/*main.c*/
#include<stdio.h>
#include"mytest.h"
int main(int argc,char*argv[])
{
test1();
test2();
return 0;
}
在普通编译时是用: gcc -o main main.c test1.c test2.c mytest.h 生成可执行文件main
但现在要把 test1.c test2.c mytest.h 编译成库供主函数调用,具体命令如下:
生成test1.o test2.o 文件。
gcc -c test1.c test2.c
[zdg@localhost mylib]$ gcc -c test1.c test2.c
[zdg@localhost mylib]$
[zdg@localhost mylib]$ ll
total 1556
-rwxrwxrwx. 1 root root 3204 Jun 8 21:24 libtest.a
-rwxrwxrwx. 1 root root 6732 Jun 8 21:23 main
-rwxrwxrwx. 1 root root 117 Jun 8 21:17 main.c
-rwxrwxrwx. 1 root root 106 Jun 8 21:08 main.c~
-rwxrwxrwx. 1 root root 92 Jun 8 21:14 mytest.h
-rwxrwxrwx. 1 root root 80 Jun 8 20:49 mytest.h~
-rwxrwxrwx. 1 root root 1565048 Jun 8 21:20 mytest.h.gch
-rwxrwxrwx. 1 root root 99 Jun 8 21:12 test1.c
-rwxrwxrwx. 1 root root 85 Jun 8 20:49 test1.c~
-rwxrwxrwx. 1 root root 1496 Jun 8 21:25 test1.o
-rwxrwxrwx. 1 root root 98 Jun 8 21:13 test2.c
-rwxrwxrwx. 1 root root 85 Jun 8 20:50 test2.c~
-rwxrwxrwx. 1 root root 1496 Jun 8 21:25 test2.o
接下来用命令生成静态函数库:libtest.a
ar crv libtest.a test1.o test2.o
[zdg@localhost mylib]$ ar crv libtest.a test1.o test2.o
a - test1.o
a - test2.o
[zdg@localhost mylib]$
[zdg@localhost mylib]$ ll
total 1556
-rwxrwxrwx. 1 root root 3204 Jun 8 21:24 libtest.a
-rwxrwxrwx. 1 root root 6732 Jun 8 21:23 main
-rwxrwxrwx. 1 root root 117 Jun 8 21:17 main.c
-rwxrwxrwx. 1 root root 106 Jun 8 21:08 main.c~
-rwxrwxrwx. 1 root root 92 Jun 8 21:14 mytest.h
-rwxrwxrwx. 1 root root 80 Jun 8 20:49 mytest.h~
-rwxrwxrwx. 1 root root 1565048 Jun 8 21:20 mytest.h.gch
-rwxrwxrwx. 1 root root 99 Jun 8 21:12 test1.c
-rwxrwxrwx. 1 root root 85 Jun 8 20:49 test1.c~
-rwxrwxrwx. 1 root root 1496 Jun 8 21:20 test1.o
-rwxrwxrwx. 1 root root 98 Jun 8 21:13 test2.c
-rwxrwxrwx. 1 root root 85 Jun 8 20:50 test2.c~
-rwxrwxrwx. 1 root root 1496 Jun 8 21:20 test2.o
把库编译进程序:gcc -o main main.c libtest.a
[zdg@localhost mylib]$ gcc -o main main.c libtest.a
执行程序
[zdg@localhost mylib]$ ./main
test1 is done
test2 is done
也可以指定库文件路径:
gcc -o main main.c -L . -ltest
其中指令-L 说明是链接库文件,库名称是去掉libtest.a 的lib标示和后缀.a
gcc -o main main.c -L . -ltest
[zdg@localhost mylib]$
[zdg@localhost mylib]$ ls
libtest.a main main.c main.c~ mytest.h mytest.h~ mytest.h.gch test1.c test1.c~ test1.o test2.c test2.c~ test2.o
[zdg@localhost mylib]$ ./main
test1 is done
test2 is done
[zdg@localhost mylib]$