无法编译使用ncurses的C/C++代码

17

我刚刚发现了ncurses,并开始学习它,但是我的教程中的示例在我的计算机上无法编译。

我不得不手动安装ncurses,通过输入“apt-get install libncurses5-dev libncursesw5-dev”来完成。我之所以这样做是因为在此之前,我遇到了一个错误,指出我无法“#include ”。

安装它确实起作用了,但现在我却得到了另一个错误:

touzen@comp:~/learning_ncurses$ g++ -o hello_world hello_world.cpp
/tmp/ccubZbvK.o: In function `main':
hello_world.cpp:(.text+0xa): undefined reference to `initscr'
hello_world.cpp:(.text+0x16): undefined reference to `printw'
hello_world.cpp:(.text+0x1b): undefined reference to `refresh'
hello_world.cpp:(.text+0x20): undefined reference to `stdscr'
hello_world.cpp:(.text+0x28): undefined reference to `wgetch'
hello_world.cpp:(.text+0x2d): undefined reference to `endwin'
collect2: ld returned 1 exit status

我编译的代码长这样:

#include <ncurses.h>
int main(){
    initscr();
    printw("Hai thar world...");
    refresh();
    getch();
    endwin();

    return 0;
}

我为什么会得到这个错误?更重要的是,我该如何修复它?

1个回答

39

你需要链接ncurses库

g++ -o hello_world hello_world.cpp -lncurses

1
我对C++还很陌生,所以这个概念对我来说是新的。每当我使用编译器中未包含的库时,我是否总是需要这样做? - thomasvakili
3
是的。头文件允许您的代码通过将函数声明与代码中的调用进行匹配来进行编译。链接器的工作是在链接时通过指定封装库的名称(以及自己代码的目标文件)来查找程序中使用的每个函数的实际可运行代码。 - Steve Townsend
确切地说,您需要链接到所有库,包括标准库。 - Paul Beckingham
1
你到目前为止还没有意识到这一点的唯一原因是GCC自动链接libc(除非你使用-ffreestanding告诉它不要这样做)。 - Karoly Horvath
2
我和楼主遇到了完全相同的问题,但有些不同:我正在按照ncurses的非常基本的hello world教程进行学习,该教程解释了如何编译,就像这样:g++ -lncurses helloworld.cpp,这导致了与楼主相同的错误。所以我的问题是我需要解释说明-lncurses 必须在编译命令的末尾。 - aesede
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接