all:liba.alibb.atest.o gcc -o test$^liba.a:liba.oliba.h ar crv $@$<libb.a:libb.olibb.h ar crv $@$<clean: rm -rf *.o *.a *~
編譯輸出如下,正如前面的預想
Result
1234567891011121314
$ make
cc -c -o liba.o liba.c
ar crv liba.a liba.o
a - liba.o
cc -c -o libb.o libb.c
ar crv libb.a libb.o
a - libb.o
cc -c -o test.o test.c
gcc -o test liba.a libb.a test.o
test.o: In function `main':
test.c:(.text+0x5): undefined reference to `test_liba'
test.c:(.text+0xa): undefined reference to `test_libb'
collect2: ld returned 1 exit status
make: *** [all] Error 1
$ make
cc -c -o liba.o liba.c
ar crv liba.a liba.o
a - liba.o
cc -c -o test.o test.c
cc -c -o libb.o libb.c
ar crv libb.a libb.o
a - libb.o
gcc -o test liba.a test.o libb.a
test.o: In function `main':
test.c:(.text+0x5): undefined reference to `test_liba'
libb.a(libb.o): In function `test_libb':
libb.c:(.text+0x5): undefined reference to `from_liba'
collect2: ld returned 1 exit status
make: *** [all] Error 1
解法二:使用--start-group … --end-group參數
將Makefile 的gcc -o test $^改成gcc -o test -Wl,--start-group $^ -Wl,--end-group
參數說明如下
-Wl: 告訴gcc傳參數給linker
--start-group … --end-group
告訴linker在中間的...重複找尋symbol
這樣的行為有效能代價,請謹慎使用
編譯並執行結果如下
Result
12345678910111213
$ make
cc -c -o liba.o liba.c
ar crv liba.a liba.o
a - liba.o
cc -c -o libb.o libb.c
ar crv libb.a libb.o
a - libb.o
cc -c -o test.o test.c
gcc -o test -Wl,--start-group liba.a libb.a test.o -Wl,--end-group
$ ./test
from_libb
from_liba