Reputation: 487
i am trying to get continuous keyboard input in c and have tried following the answer found here. however, i am getting undefined reference
errors when using ncurses
functions.
my code:
#include <stdio.h>
#include <stdbool.h>
#include <unistd.h>
#include <ncurses.h>
typedef struct
{
int fps;
int width;
int height;
int frame;
} window;
typedef struct
{
int x;
int y;
} position;
typedef struct
{
position pos;
} snake;
int kbhit(void)
{
int ch = getch();
if (ch != ERR)
{
ungetch(ch);
return 1;
}
else
{
return 0;
}
}
void draw(window win, snake s)
{
for (int i = -1; i <= win.height; i++)
{
for (int j = -1; j <= win.width; j++)
{
if ((i == -1 || i == win.height) || (j == -1 || j == win.width))
{
printf("#");
}
else if (j == s.pos.x && i == s.pos.y)
{
printf("O");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
int main()
{
printf("Welcome to the Snake Game\n");
sleep(3);
window win = {1, 20, 10, 0};
snake s = {{19, 9}};
int key_code;
initscr();
cbreak();
noecho();
nodelay(stdscr, TRUE);
scrollok(stdscr, TRUE);
while (true)
{
printf("\e[1;1H\e[2J");
printf("%d\n", win.frame);
draw(win, s);
if (kbhit())
{
key_code = getch();
printf("%d", key_code);
}
usleep((int)((1.0 / win.fps) * 1000) * 1000);
win.frame++;
}
return 0;
}
output:
/usr/bin/ld: /tmp/ccZ2eIK1.o: in function `kbhit':
game.c:(.text+0xf): undefined reference to `stdscr'
/usr/bin/ld: game.c:(.text+0x17): undefined reference to `wgetch'
/usr/bin/ld: game.c:(.text+0x2a): undefined reference to `ungetch'
/usr/bin/ld: /tmp/ccZ2eIK1.o: in function `main':
game.c:(.text+0x136): undefined reference to `initscr'
/usr/bin/ld: game.c:(.text+0x13b): undefined reference to `cbreak'
/usr/bin/ld: game.c:(.text+0x140): undefined reference to `noecho'
/usr/bin/ld: game.c:(.text+0x147): undefined reference to `stdscr'
/usr/bin/ld: game.c:(.text+0x154): undefined reference to `nodelay'
/usr/bin/ld: game.c:(.text+0x15b): undefined reference to `stdscr'
/usr/bin/ld: game.c:(.text+0x168): undefined reference to `scrollok'
/usr/bin/ld: game.c:(.text+0x1b6): undefined reference to `stdscr'
/usr/bin/ld: game.c:(.text+0x1be): undefined reference to `wgetch'
collect2: error: ld returned 1 exit status
Upvotes: 0
Views: 491
Reputation: 109
You must include the NCURSES library with the link. A portable way to do this is like this:
$ gcc -o game game.c $( pkg-config --cflags --libs mcurses )
Or just include the "-lncurses" library as mentioned previously.
On an RPM-based system, you'll need the ncurses-devel package installed on the build machine.
Upvotes: 2