user6299344
user6299344

Reputation:

getting a char from keyboard using curses.h

I'm trying to get a character from the keyboard using curses.h. This is my source (get_char_example.c):

#include <curses.h>
#include <stdio.h>

int main(void)
{
    char ch;

    printf("Enter a character: ");
    ch = getch();
    printf("\nIts ASCII code is %d\n", ch);

    return 0;
}

I use the following command to compile:

gcc get_char_example.c -o get_char_example

And I get the following error:

/tmp/ccjaXwRU.o: In function `main':

get_char_example.c:(.text+0x1c): undefined reference to `stdscr'
get_char_example.c:(.text+0x24): undefined reference to `wgetch'
collect2: error: ld returned 1 exit status

using: gcc (GCC) 7.2.0 Arch Linux 4.13.9-1-ARCH

Thanks in advance!

Upvotes: 2

Views: 1273

Answers (1)

It is a linker error (see this, nearly a duplicate). ncurses is generally known to pkg-config (which gives more dependencies, when required), so try to compile with:

 gcc -Wall -Wextra -g \
    $(pkg-config --cflags ncurses) \
    get_char_example.c \
    $(pkg-config --libs ncurses)

You want to Invoke GCC with all warnings and debug info; you would use GDB, perhaps under emacs or with ddd, for debugging.

Even better, use some build automation tool (like make or ninja). With GNU make take inspiration from this to write your Makefile (where tab-s are significant).

On my Debian Sid, pkg-config --cflags ncurses gives -D_GNU_SOURCE -D_DEFAULT_SOURCE and pkg-config --libs ncurses gives -lncurses -ltinfo, so simply linking with -lncurses is not enough (and that is why this is not exactly a duplicate today in November 2017; a few years ago linking with simply -lncurses was enough, today it is not).

Use pkg-config --list-all to find all the packages and libraries known to pkg-config; when developing your libraries consider also providing some .pc file for it.

BTW, your program should start by initializing with initscr and use printw; Read Ncurses-programming-HowTo even if it is a bit old.

Notice also that using ASCII in the 21st century is obsolete. Programs and computers use UTF-8 everywhere, and this has profound consequences you should be aware of (since an UTF-8 character can span several bytes). My French keyboard has keys for ², §, and é (even with American keyboards your could paste them) and none of these are in ASCII. Consider also using some UTF-8 library like libunistring.

Upvotes: 3

Related Questions