如何在Linux上安装ncurses库
时间:2020-01-09 10:41:39 来源:igfitidea点击:
如何使用ncurses库和头文件来编译应用程序。
如何在Linux操作系统上安装install ncurses库和头文件?
如何使用ncurses编写一个简单的hello world程序并将其在Linux上编译?
GNU ncurses是用于控制在Unix,Linux和其他操作系统下写入控制台屏幕的软件API。
您可以使用ncurses库在Linux或类似Unix的系统上创建基于文本的用户界面(TUI)。
在Debian/Ubuntu Linux中安装ncurses库
- 您需要安装以下两个软件包:
libncurses5-dev
:ncurses的开发者库libncursesw5-dev
:ncursesw的开发者库。 - 打开终端应用程序。
- 执行以下apt-get命令以安装ncurses标头和libs:
sudo apt-get install libncurses5-dev libncursesw5-dev
在CentOS/RHEL/Scientific Linux 6.x/7.x +和Fedora Linux 21或更早版本中安装ncurses库
- 您需要安装以下软件包:
ncurses-devel
:ncurses的开发人员库 - 执行以下yum命令来安装ncurses头文件和lib:
sudo yum install ncurses-devel
在Fedora Linux 22.x +中安装ncurses库
- 您需要安装以下软件包:
ncurses-devel
:ncurses的开发人员库 - 执行以下dnf命令以安装ncurses标头和库:
sudo dnf install ncurses-devel
如何编译C程序并使用ncurses库?
创建一个名为hello.c的测试程序,如下所示:
#include <ncurses.h> int main(void){ initscr(); /* Start curses mode */ printw("Hello World !!!"); /* Print Hello World */ refresh(); /* Print it on to the real screen */ getch(); /* Wait for user input */ endwin(); /* End curses mode */ return 0; }
首先,请确保在Linux上安装GNU/GCC C编译器:
- CentOS/RHEL 7:安装GCC(C和C ++编译器)和开发工具
- Debian Linux安装GNU GCC编译器和开发环境
要链接到ncurses库,请将-Incurses
选项传递给gcc/cc命令:
$ cc -o output input.c -lncurses $ cc -o hello hello.c -lncurses
运行:
$ ./hello
输出示例:
Hello World !!!
这是另一个程序:
/* CURWIN1.C ========= (c) Copyright Paul Griffiths 1999 Email: [email protected] Moving windows with ncurses. */ #include <stdlib.h> #include <stdio.h> #include <curses.h> int main(void) { WINDOW * mainwin, * childwin; int ch; /* Set the dimensions and initial position for our child window */ int width = 23, height = 7; int rows = 25, cols = 80; int x = (cols - width) / 2; int y = (rows - height) / 2; /* Initialize ncurses */ if ( (mainwin = initscr()) == NULL ) { fprintf(stderr, "Error initialising ncurses.\n"); exit(EXIT_FAILURE); } /* Switch of echoing and enable keypad (for arrow keys) */ noecho(); keypad(mainwin, TRUE); /* Make our child window, and add a border and some text to it. */ childwin = subwin(mainwin, height, width, y, x); box(childwin, 0, 0); mvwaddstr(childwin, 1, 4, "Move the window"); mvwaddstr(childwin, 2, 2, "with the arrow keys"); mvwaddstr(childwin, 3, 6, "or HOME/END"); mvwaddstr(childwin, 5, 3, "Press 'q' to quit"); refresh(); /* Loop until user hits 'q' to quit */ while ( (ch = getch()) != 'q' ) { switch ( ch ) { case KEY_UP: if ( y > 0 ) --y; break; case KEY_DOWN: if ( y < (rows - height) ) ++y; break; case KEY_LEFT: if ( x > 0 ) --x; break; case KEY_RIGHT: if ( x < (cols - width) ) ++x; break; case KEY_HOME: x = 0; y = 0; break; case KEY_END: x = (cols - width); y = (rows - height); break; } mvwin(childwin, y, x); } /* Clean up after ourselves */ delwin(childwin); delwin(mainwin); endwin(); refresh(); return EXIT_SUCCESS; }
编译并运行如下:
$ cc -o curwin1 curwin1.c -lncurses $ ./curwin1