本文爲原創文章,轉載需指明該文連接函數
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 以後,就再也不出現該問題。