Showing posts with label gcc linux link. Show all posts
Showing posts with label gcc linux link. Show all posts

Wednesday, October 3, 2012

Linker的問題

最近Build Embedded System的程式,在寫Makefile的時候,有一個問題我竟然花了快1個小時才解決.


通常我們再寫大程式的時候(有許多程式),透過Makefile順利地將所有source code compile成計算機可以讀的OBJ檔.但是所有的obj檔要合併成一個真正的可執行檔則必須透過Linker的方式去重組裡面的程式位址(reloacation).


底下的指令是我原本寫的


$(LD) $^ -o sample.elf -nostartfiles $(LDFLAGS)

結果每次執行的結果

unreferenced to 'print'

類似這樣的錯誤訊息,這個錯誤訊息代表著你的程式裡面有用到外部的一個函式(不是在同一個檔案裡面),必須要參考到外部的函式的位址,這樣Linker程式才可以正確地算出所要呼叫的位址.
我都以為這樣的寫法沒有錯,害我以為是不是Linker的問題,還是其他問題.

結果我也不知道怎麼想的,我就把它的位置調整一下試試看
$(LD) -nostartfiles $^ -o sample.elf $(LDFLAGS)

再執行一次,竟然成功了!!

我想有可能Cross Compiler寫的沒有那麼smart.所以才會這樣!!

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。