Monday, December 21, 2009

compiler的問題

最近有遇到compiler的問題

廠商有提供幾個library給我們使用,libcommon.a

而我自己寫了幾個測試程式要來測試這個library能不能使用。

當我寫完以後要compiler成執行檔結果就發生底下的問題

#gcc -O3 -I../Include -c Testlib.c
#gcc -L../lib -lcommon Testlib.o -o Testlib
Testlib.o: In function `main':
Testlib.o(.text+0x44): undefined reference to `Lib_Init'
Testlib.o(.text+0x7c): undefined reference to `Lib_Write'
Testlib.o(.text+0x98): undefined reference to `Lib_UnInit'
collect2: ld returned 1 exit status


疑~~~奇怪了,明明Lib_Init,Lib_Write和Lib_Uninit都在libcommon.a裡面啊??

上網找尋gcc的使用手冊
-l library
Search the library named library when linking. (The second alternative with the library as a separate argument is only for POSIX compliance and is not recommended.)

It makes a difference where in the command you write this option; the linker searches and processes libraries and object files in the order they are specified. Thus, `foo.o -lz bar.o' searches library `z' after file foo.o but before bar.o. If bar.o refers to functions in `z', those functions may not be loaded.

喔~~真相大白,原來gcc使用library也有順序可言喔!!

只要將
gcc -L../lib -lcommon Testlib.o -o Testlib
改成
gcc Testlib.o -L../lib -lcommon -o Testlib
這樣就可以了。

就以我這個例子來說,Testlib.o裡面有參考到libcommon.a裡面所提供的function,所以要放在libcommon.a之前,這樣gcc就會把undefine的symbol先找出來再往後找尋library。

No comments: