How do I create simplistic window-like elements in a command-line program?

Solution 1:

The text-based window-like interface, contained within a terminal, that you see when you run sudo dpkg-reconfigure lightdm is coded using the ncurses library. So if you want your program to provide an interface that looks like that, you can use ncurses too.

  • Here's the ncurses project page.

  • Here's an NCURSES Programming HOWTO.

  • You can install some ncurses documentation files with the ncurses-doc Install ncurses-doc package.

    This includes the ncurses manpage, which you can also view online here. It also includes manual pages for all the functions provided by the ncurses library (some share a manpage). Those manpages are not currently online at manpages.ubuntu.com.

To build software using ncurses in Ubuntu, you should get the appropriate header files package. Unless you're cross-compiling, this will be:

  • For programs using traditional strings where most characters are represented by a single byte (for example, UTF-8), use libncurses5 Install libncurses5.

    This is probably what you want if your strings are arrays of char (in C and other C-based languages) or std::string (in C++).

  • For programs requiring wide character support, use libncursesw5 Install libncursesw5.

    You'll especially need this if your strings are arrays of wchar_t (in C and other C-based languages) or std::wstring, std::u16string, or std::u32string (in C++).

Optionally, for help debugging your program, you might also want debug symbols (for debuggers such as gdb). For that, install libncurses5-dbg Install libncurses5-dbg or libncursesw5-dbg Install libncursesw5-dbg too.

See also the ncurses in Ubuntu page on Launchpad, which contains a list of the major ncurses packages in Ubuntu as well as version information for each currently supported Ubuntu release.

When you build your program with GCC (e.g., with the gcc or g++ commands), give it the argument -lncurses or -lncursesw, usually at the very end of the command. This links your program to the ncurses library. For example:

g++ -Wall -g -o hello hello.cpp -lncurses

That compiles hello.cpp to produce an executable with debug symbols (-g), called hello (-o hello), warning on most things you might want a warning about (-Wall), and linking to the regular (not wide character) ncurses library (-lncurses).