User Tools

Site Tools


programming:ncurses

Using ncurses with C

Installation

Where to get gnu.org Project Homepage

sudo yum install ncurses ncurses-devel ncurses-libs ncures-static

IDE

I use codeblocks available in the EPEL repo.

sudo yum install codeblocks

Linking

Code::Blocks

In codeblocks click Project → Build Options… There you can reference the library under the Linker Options Tab

GCC

gcc main.c -lncurses

Debugging with GCC

Enable debugging

First make sure you have the debug tools installed.

sudo debuginfo-install glibc-2.12-1.209.el6_9.2.x86_64 ncurses-libs-5.7-4.20090207.el6.x86_64

Then we can use dgb do actually debug. First we have to compile the project with the -g option.

(~/code/snake) skull@dc:# cc main.c -o snake -lncurses -g

Then we can start the debugger with

gdb snake

Or of course we can just combine it

(~/code/snake) skull@dc:# cc main.c -o snake -lncurses -g && gdm snake
Useful gdb commands

= break [linenumber] = Break will break at the inserted linenumber.

(gdb) break 82
Breakpoint 1 at 0x4009ab: file main.c, line 82.

Once we reached the breakpoint at we can do all sorts of things.

command effect
p [variable] (or print [variable]) prints a variable
c (or continue) continues until next breakpoint
n (or next) execute next line as single instruction
s (or step) same es next but doesn't treat the next line as single instruction
l (or list) prints the list
enter repeats last command

Basic Functionality of ncurses

#include <stdio.h>
#include <stdlib.h>
#include <ncurses.h>
 
int main()
{
    initscr(); // Inits ncurses
    noecho();  // supresses the output of input characters
    refresh(); // reloads all pending outputs. makes changes visible.
 
    mvprintw(0,0,"Hello World!");
 
    getch();   // so that we cann see the hello world.
 
    echo();    // activates echo again.
 
    /* In order to clean up after the ncurses routines,
       the routine endwin() is provided.
       It restores tty modes to what they were when initscr() was first called,
       and moves the cursor down to the lower-left corner.
       Thus, anytime after the call to initscr, endwin() should be called before exiting. */
    endwin();
 
    return 0;
}

move() and the cursor position

It's important to know that after the use of mvprintw(y,x,“Hello World!”) the cursor gets set to the y and x position. So if for examlpe we want to use it in a game and make sure that the cursor is always at the player position, we have to use move() to move the cursor. Take this little method for example:

void PlayerMove(int y, int x, Player * unit)
{
    // Print . where Player was.
    mvprintw(unit->position.y, unit->position.x, ".");
 
    // Reposition user
    unit->position.x = x;
    unit->position.y = y;
 
    //Move User
    mvprintw(unit->position.y, unit->position.x, "@");
 
    // Move Cursor
    move(unit->position.y, unit->position.x);
}
programming/ncurses.txt · Last modified: 2017/07/08 18:43 by skull@darktemple.ch