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

Tou*_*zen 15 c c++ compiler-errors ncurses

我刚刚发现了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
Run Code Online (Sandbox Code Playgroud)

我编译的代码如下所示:

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

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么我会收到此错误.更重要的是,我该如何解决这个问题呢?

Kar*_*ath 33

你必须链接ncurses库

g++ -o hello_world hello_world.cpp -lncurses
Run Code Online (Sandbox Code Playgroud)

  • 是.头文件允许通过将函数声明与代码中的调用进行匹配来编译代码.链接器的工作是为程序中使用的每个函数找到*实际可运行代码*,这是通过在链接时指定封装库名称(以及您自己代码的目标文件). (3认同)
  • 与 OP 有完全相同的问题,但有点不同:我正在关注 ncurses 的非常基本的 hello world 教程,该教程解释了如何编译,如下所示:`g++ -lncurses helloworld.cpp` 给出与 OP 相同的错误。所以我的问题是我需要解释`-lncurses` **必须在编译命令的末尾。** (2认同)