本文为原创文章,转载需指明该文连接函数
1.代码目录结构以下: spa
1 comm/errorhandler.c
2 comm/inc/apue.h
3 atexit.c 4 Makefile
5 6 staticlib/lib/ 7 staticlib/inc/staticlibs.h 8 staticlib/staticlib_add.c 9 staticlib/staticlib_mul.c 10 staticlib/Makefile
2.目录 staticlib/lib/ 是用来盛放静态库文件的——libmytest.a,在编译静态库以前该目录是空的code
staticlib/inc/staticlibs.h 头文件内容以下:blog
1 #ifndef __staticlibs_h
2 #define __staticlibs_h
3 int static_lib_func_add(int i1, int i2); 4 int static_lib_func_mul(int i1, int i2);
5 #endif
staticlib/staticlib_add.c 文件内容以下:it
1 #include "apue.h" 2 int static_lib_func_add(int i1, int i2) 3 { 4 int iret = i1 + i2; 5 printf("in a static library, return value %d\n", iret); 6 return iret; 7 }
staticlib/staticlib_mul.c 文件内容以下:编译
1 #include "apue.h" 2 3 int static_lib_func_mul(int i1, int i2) 4 { 5 int iret = i1 * i2; 6 printf("in a static library, return value is %d\n", iret); 7 return iret; 8 }
staticlib/Makefile 文件内容以下:class
1 CC = gcc 2 CFLAGS = -Wall -O -g 3 CXXFLAGS = 4 INCLUDE = -I ./inc -I ../comm/inc 5 TARGET = libmytest.a 6 LIBPATH = ./lib/ 7 8 vpath %.h ./inc 9 10 OBJS = staticlib_add.o staticlib_mul.o 11 SRCS = staticlib_add.c staticlib_mul.c 12 13 $(OBJS):$(SRCS) 14 $(CC) $(CFLAGS) $(INCLUDE) -c $^ 15 16 all:$(OBJS) 17 ar rcs $(TARGET) $^ 打包 .o 文件到库文件 libmytest.a 18 mv $(TARGET) $(LIBPATH) 19 20 clean: 21 rm -f *.o 22 rm -f $(LIBPATH)*
3.文件 atexit.c 的内容以下:test
1 #include "apue.h" 2 #include "staticlibs.h" //包含静态库的头文件 3 4 static void my_exit1(void); 5 static void my_exit2(void); 6 7 int main(void) 8 { 9 static_lib_func_add(1, 9); //静态库函数 10 static_lib_func_mul(1, 9); //静态库函数 11 12 if(0 != atexit(my_exit2)) 13 err_sys("can't register my_exit2"); 14 if(0 != atexit(my_exit1)) 15 err_sys("can't register my_exit1"); 16 if(0 != atexit(my_exit1)) 17 err_sys("can't register my_exit1"); 18 printf("main is done\n"); 19 return 0; 20 } 21 22 static void my_exit1(void) 23 { 24 printf("first exit handler\n"); 25 } 26 27 static void my_exit2() 28 { 29 printf("second exit handler\n"); 30 }
文件 Makefile 的内容以下:cli
1 CC = gcc 2 CFLAGS = -Wall -O -g 3 CXXFLAGS = 4 INCLUDE = -I ./comm/inc -I ./staticlib/inc 5 TARGET = atexit 6 LIBVAR = -lmytest 连接 libmytest.a 7 LIBPATH = -L./staticlib/lib 8 #search paths for errorhandler.c 9 vpath %.c ./comm 10 #下行是为依赖项 apue.h 准备的,好比 [errorhandler.o:errorhandler.c apue.h] 里的 apue.h 11 vpath %.h ./comm/inc 12 13 OBJS = errorhandler.o atexit.o 14 #下行的 apue.h,能够没必要写出来 15 errorhandler.o:errorhandler.c apue.h 16 $(CC) $(CFLAGS) $(INCLUDE) -c $^ 17 atexit.o:atexit.c apue.h 18 $(CC) $(CFLAGS) $(INCLUDE) -c $^ 19 20 all:$(OBJS) $(LIB) 21 cd ./staticlib && make all 执行staticlib/Makefile 里的 make all 22 $(CC) $(CFLAGS) $(INCLUDE) -o $(TARGET) $(OBJS) $(LIBVAR) $(LIBPATH) 23 24 clean: 25 rm -f *.o 26 rm -f $(TARGET) 27 cd ./staticlib && make clean 执行staticlib/Makefile 里的 make clean
我在编译的过程当中出现了 /usr/bin/ld: cannot find -lc,而后在系统上 locate libc.a,发现系统上没有 libc.a 静态库文件,gcc
这是因为个人系统还没安装glibc的静态版本,安装 glibc-static-2.12-1.107.el6.x86_64.rpm 以后,就再也不出现该问题。