ncurses 库的问题

问题描述

我试图在 c 中获得连续的键盘输入,并尝试按照 here 找到的答案进行操作。但是,我在使用 undefined reference 函数时遇到 ncurses 错误

我的代码

#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;
}

输出

/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

解决方法

您必须在链接中包含 NCURSES 库。一种可移植的方法是这样的:

$ gcc -o game game.c $( pkg-config --cflags --libs mcurses )

或者只包含前面提到的“-lncurses”库。

在基于 RPM 的系统上,您需要在构建机器上安装 ncurses-devel 包。