Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

把 .o 目標檔當執行檔跑?syntax error: word unexpected 的真相

不小心把編譯出來的目標檔丟到開發板上執行,結果得到一句莫名其妙的 syntax error: word unexpected (expecting ")")。一個簡單的 hello world 怎麼會出錯?問題其實出在 -c 這個編譯選項。

為什麼 PC 與 ARM 的提示差這麼多

gcc -c 產出的是不可執行的目標檔,在 PC 上執行會直接得到清楚訊息:

~/test$ ./zh_display.o
-bash: ./zh_display.o: cannot execute binary file

但在 ARM 上卻是:

$ ./hello_qt
./hello_qt: line 1: syntax error: word unexpected (expecting ")")

原因是檔案被轉到 Windows 工作台再 tftp 下載回開發板後,全部變成普通檔案,自己 chmod +x 加上執行權,於是 shell 試著把它當腳本解讀,才吐出這種看不懂的錯誤。

用 file 快速分辨

~/test$ file hello_qt
hello_qt: ELF 32-bit LSB executable, ARM, version 1, dynamically linked (uses shared libs), not stripped

~/test$ file hello_qt.o
hello_qt.o: ELF 32-bit LSB relocatable, ARM, version 1, not stripped

兩者都是 ELF,但目標檔是 relocatable,執行檔是 executable,一字之差決定能不能跑。

用 readelf 看關鍵欄位

~/test$ readelf -h hello_qt
ELF Header:
  Class:   ELF32
  Type:    EXEC (Executable file)
  Machine: ARM
  Entry point address: 0x87f8
  Number of program headers: 6

~/test$ readelf -h hello_qt.o
ELF Header:
  Class:   ELF32
  Type:    REL (Relocatable file)
  Machine: ARM
  Entry point address: 0x0
  Number of program headers: 0

-h 會讀出 ELF 檔頭,其中兩項最關鍵:Type 對應 file 看到的檔案類型;Entry point address 是執行入口點,只有可執行檔才有值,目標檔屬於可重定位檔、還不能直接執行,因此為 0。目標檔甚至連 program header 都沒有。

養成習慣:交叉編譯後先 file 一下,能省下不少瞎猜的時間。

Copyright © Linux教程網 All Rights Reserved