想在 Linux 上用 curses.h 寫個圖形介面,結果第一次編譯就被賞了一巴掌:
hello.c:1: fatal error: curses.h: No such file or directory
上網查了才知道,問題不在程式碼,而是根本沒安裝 curses 開發庫。多數發行版預設只裝了執行庫,標頭檔要另外補。
以 Debian/Ubuntu 系為例,用新得立(Synaptic)搜尋並安裝 libncurses5-dev 即可;其他發行版則對應安裝 ncurses 的 devel 套件。
#include <curses.h>
int main()
{
initscr();
clear();
move(10, 20);
addstr("Hello world");
move(LINES - 1, 0);
refresh();
getch();
endwin();
return 0;
}
幾個關鍵 API 值得記一下:initscr() 初始化螢幕並取得 stdscr,clear() 清屏,move() 移動游標,addstr() 寫入字串,refresh() 把虛擬畫面實際刷到終端,getch() 等待按鍵,最後 endwin() 還原終端狀態。
照直覺下指令:
gcc -o hello hello.c -Incurses
結果跳出一大串 undefined reference:
/tmp/ccsmlmYV.o: In function `main': hello.c:(.text+0xa): undefined reference to `initscr' hello.c:(.text+0xf): undefined reference to `stdscr' hello.c:(.text+0x17): undefined reference to `wclear' hello.c:(.text+0x1c): undefined reference to `stdscr' hello.c:(.text+0x34): undefined reference to `wmove' hello.c:(.text+0x51): undefined reference to `waddnstr' hello.c:(.text+0x56): undefined reference to `LINES' hello.c:(.text+0x72): undefined reference to `wrefresh' hello.c:(.text+0x8c): undefined reference to `wgetch' hello.c:(.text+0x91): undefined reference to `endwin' collect2: ld returned 1 exit status
這裡有兩個觀念要釐清:-I 只管標頭檔搜尋路徑,跟連結完全無關;而這些符號全找不到,代表連結器沒有拿到 ncurses 的函式庫。
gcc hello.c -o hello -I/usr/include -L/usr/lib -lncurses
三個參數各有分工:-I 指定標頭檔位置、-L 指定函式庫位置、-l 指定要連結的庫(-lncurses 會去找 libncurses.so)。編譯通過,執行後終端會進入 curses 模式並顯示 Hello world。
小結:遇到「No such file」是缺標頭檔,遇到「undefined reference」是缺函式庫,兩者解法完全不同,分清楚就能少繞很多路。