Linux 下 C/C++ 開發常遇到各類編譯、連結、執行錯誤。本文整理高頻錯誤訊息、根因與修正方法,適合開發者快速查閱。
Makefile 語法錯誤
| 錯誤訊息 | 原因 | 解決 |
Makefile:2: *** missing separator. Stop. | 指令行前缺少 Tab 鍵(空格無效) | 確保每條指令以單一 Tab 開頭 |
bash: ./Makefile: Permission denied | 直接執行 Makefile 文本檔 | 使用 make 指令;非標準檔名用 make -f Makefile.am |
原始碼字元編碼問題
| 錯誤訊息 | 原因 | 解決 |
stray '\200' in program
stray '\343' in program | 原始碼混入中文標點(;,}、+)或全形空格 | 關閉中文輸入法,刪除並重新輸入該行;或用 iconv 轉碼 |
缺少標頭檔導致的隱式宣告警告/錯誤
| 警告/錯誤 | 缺少標頭檔 | 補充指令 |
implicit declaration of 'printf' | stdio.h | #include <stdio.h> |
implicit declaration of 'malloc' | malloc.h 或 stdlib.h | #include <stdlib.h> |
implicit declaration of 'exit' | stdlib.h | #include <stdlib.h> |
implicit declaration of 'execlp' | unistd.h | #include <unistd.h> |
implicit declaration of 'strlen' | string.h | #include <string.h> |
'FILE' undeclared | stdio.h | #include <stdio.h> |
'O_RDONLY' undeclared | fcntl.h | #include <fcntl.h> |
'CLONE_VM', 'CLONE_FILES' undeclared | sched.h | #include <sched.h> |
'pid_t' undeclared | sys/types.h(或 stdlib.h) | #include <sys/types.h> |
System V IPC semun 結構體未定義
錯誤: storage size of 'options' isn't known(union semun options;)
原因: /usr/include/linux/ipc.h 定義了 semun,但 POSIX 標準 sys/ipc.h、sys/sem.h 未定義。
解決: 自行定義:
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;
字串長度與 sizeof 差異
- C 風格字串以
'\0' 結尾。
sizeof(str) 包含結尾 '\0'。
strlen(str) 不包含 '\0'。
open() vs fopen() 差異速查
| 特性 | open() | fopen() |
| 標頭檔 | fcntl.h, sys/types.h, sys/stat.h | stdio.h |
| 回傳值 | 檔案描述符 | FILE* 指標 |
| 層級 | 系統呼叫 | 標準庫緩衝 I/O |
| 適用 | 底層控制、非阻塞、鎖 | 一般文字/二進位檔處理 |
除錯小技巧
- 編譯加
-Wall -Wextra -Werror 將警告視為錯誤,強制修正。
- 用
gcc -E 預處理輸出檢查巨集展開結果。
strace ./a.out 追蹤系統呼叫定位執行期錯誤。