執行目標檔案引發的問題:syntax error: word unexpected 今天不小心把一個目標檔案當成了可執行檔放到開發板上進行執行,結果出現了這樣一個問題:./hello_qt: line 1: syntax error: word unexpected (expecting ")"),因為以前沒有碰到過這事,一時間有點蒙,就是一個簡單的hello world按道理不會有問題才對。於是google了一下,原來是一個小小的-c編譯選項搞得鬼。順帶也擴充學習總結了一下。 arm和pc上執行目標檔案的區別一般來說,gcc -c選項編譯出來的目標檔案是不可執行檔,因此也就不會遇到這種問題,尤其是在PC上就更是如此。我這邊是因為把檔案轉windows工作台,再通過tftp下載的開發板上,然後檔案就全部是普通檔案,都是自己chmod +x改的可執行,一時大意才難得碰上這問題。 PC上執行目標檔案的錯誤提示1~/test$ ./zh_display.o2-bash: ./zh_display.o: cannot execute binary fileARM上執行交叉編譯目標檔案的錯誤提示1$ ./hello_qt2./hello_qt: line 1: syntax error: word unexpected (expecting ")")PC上的提示資訊一看就懂,而ARM上的就會讓人莫名奇妙了。一開始我懷疑是自己代碼有問題,還反覆檢查了一遍,幸好只是一個簡單的hello world程式,不然夠我鬱悶的。也多虧我及時google,否則還不知道要浪費多少時間在這小問題上,有時候google真的很重要呀!!區分目標檔案和可執行檔目標檔案和可執行檔平時都是很容易區分的,所以一般也不會注意這個。不過從今天的問題上,我又學到了不少關於兩者差別的東西,還有區分兩者的Linux工具。 file工具:查看檔案的基本屬性資訊1~/test$ file hello_qt2hello_qt: ELF 32-bit LSB executable, ARM, version 1, dynamically linked (uses shared libs), not stripped3 4~/test$ file hello_qt.o5hello_qt.o: ELF 32-bit LSB relocatable, ARM, version 1, not stripped兩者均是ELF檔案,但是目標檔案是:relocatable, 而可執行檔是: executable。 readelf工具:查看ELF檔案的詳細資料01~/test$ readelf -h hello_qt02ELF Header:03 Magic: 7f 45 4c 46 01 01 01 61 00 00 00 00 00 00 00 0004 Class: ELF3205 Data: 2's complement, little endian06 Version: 1 (current)07 OS/ABI: ARM08 ABI Version: 009 Type: EXEC (Executable file)10 Machine: ARM11 Version: 0x112 Entry point address: 0x87f813 Start of program headers: 52 (bytes into file)14 Start of section headers: 3948 (bytes into file)15 Flags: 0x202, has entry point, GNU EABI, software FP16 Size of this header: 52 (bytes)17 Size of program headers: 32 (bytes)18 Number of program headers: 619 Size of section headers: 40 (bytes)20 Number of section headers: 2721 Section header string table index: 2422 23~/test$ readelf -h hello_qt.o24ELF Header:25 Magic: 7f 45 4c 46 01 01 01 61 00 00 00 00 00 00 00 0026 Class: ELF3227 Data: 2's complement, little endian28 Version: 1 (current)29 OS/ABI: ARM30 ABI Version: 031 Type: REL (Relocatable file)32 Machine: ARM33 Version: 0x134 Entry point address: 0x035 Start of program headers: 0 (bytes into file)36 Start of section headers: 1040 (bytes into file)37 Flags: 0x200, GNU EABI, software FP38 Size of this header: 52 (bytes)39 Size of program headers: 0 (bytes)40 Number of program headers: 041 Size of section headers: 40 (bytes)42 Number of section headers: 1643 Section header string table index: 13-h選項讀取ELF檔案的檔案頭資訊,注意其中的兩項值:Type 和 Entry point address。Type資訊就是file中的檔案類型,而 Entry point address表示檔案的執行進入點,只有可執行檔該項才有值,而目標檔案是可重新導向檔案,還不可以直接執行,因此該項值為0.目標檔案兩者為: 1Type: REL (Relocatable file)2Entry point address: 0x0而可執行檔兩者為:1Type: EXEC (Executable file)2Entry point address: 0x87f8