2011-06-25 72 views
0

我需要知道如何使用getche()函數編譯C程序,但不需要compilling,因爲它需要引用。有人知道缺少什麼參考?使用這種COMAND我想在終端上通過gcc在linux上使用getche()

IM:

的gcc -o FILENAME.C高管

+1

你是什麼意思「需要參考」?你能粘貼確切的錯誤信息嗎? (另外,'exec'似乎是一個糟糕的名字選擇,因爲它是內置的shell。) – andrewdski

+0

@andrewdski:我懷疑Duracell看到鏈接器錯誤消息「未定義引用'getche''」,並且沒有知道這意味着什麼。 @Duracell:「未定義的引用」是GNU鏈接器公認的不太明顯的方式,告訴你既沒有列出任何文件和庫,也沒有默認包含的系統庫定義了一個函數(或全局變量)你的程序*引用*。在這種情況下,這是因爲'getch [e]'是Unix永遠不可用的DOSisms - 請參閱我的理想答案*應該使用的答案,或Dan的快速解決方案。 – zwol

回答

2

從​​

/* 
    getch() and getche() functionality for UNIX, 
    based on termios (terminal handling functions) 

    This code snippet was written by Wesley Stessens ([email protected]) 
    It is released in the Public Domain. 
*/ 

#include <termios.h> 
#include <stdio.h> 

static struct termios old, new; 

/* Initialize new terminal i/o settings */ 
void initTermios(int echo) { 
    tcgetattr(0, &old); /* grab old terminal i/o settings */ 
    new = old; /* make new settings same as old settings */ 
    new.c_lflag &= ~ICANON; /* disable buffered i/o */ 
    new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ 
    tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */ 
} 

/* Restore old terminal i/o settings */ 
void resetTermios(void) { 
    tcsetattr(0, TCSANOW, &old); 
} 

/* Read 1 character - echo defines echo mode */ 
char getch_(int echo) { 
    char ch; 
    initTermios(echo); 
    ch = getchar(); 
    resetTermios(); 
    return ch; 
} 

/* Read 1 character without echo */ 
char getch(void) { 
    return getch_(0); 
} 

/* Read 1 character with echo */ 
char getche(void) { 
    return getch_(1); 
} 

/* Let's test it out */ 
int main(void) { 
    char c; 
    printf("(getche example) please type a letter: "); 
    c = getche(); 
    printf("\nYou typed: %c\n", c); 
    printf("(getch example) please type a letter..."); 
    c = getch(); 
    printf("\nYou typed: %c\n", c); 
    return 0; 
} 
3

對於Linux和其他Unix平臺上,你可能想使用ncurses,而不是隻是想模仿getch [e]。這是一個稍微涉及到的API,但它會爲你處理所有棘手的問題,Dan D.所發佈的簡單模擬不會。 (例如,如果用戶輸入^C^Z,則確實如此。)