ncurses 不适用于 -lncurses

ncurses doesn't work with -lncurses

我尝试在 Ubuntu 12.04 LTS 中使用 ncurses 库。它不起作用。 我一步一步来:

  1. 安装:

    
    sudo apt-get update
    sudo apt-get install libncurses-dev
    </pre>

  2. main.cpp:

    #include <curses.h>
    #include <ncurses.h>
    int main(int argc, char *argv[])
    {
        initscr();      // Start curses mode
        printw("Hello World !!!");
        refresh();      // Print it on to the real screen
        getch();        // Wait for user input
        endwin();       // End curses mode
    }
    
  3. makefile,将-lncurses添加到link并编译:

    
    all: main
    OBJS = main.o
    CXXFLAGS  += -std=c++0x
    CXXFLAGS  += -c -Wall
    main: $(OBJS)
        g++ -lncurses $^ -o $@
    %.o: %.cpp %.h
        g++ $(CXXFLAGS) -lncurses $<
    main.o: main.cpp
    clean:
        rm -rf *.o *.d main
        reset
    run:
        ./main
    </pre>

  4. 构建(出现错误):

    $ make
    g++ -std=c++0x -c -Wall   -c -o main.o main.cpp
    g++ -lncurses main.o -o main
    main.o: In function `main':
    main.cpp:(.text+0xa): undefined reference to `initscr'
    main.cpp:(.text+0x16): undefined reference to `printw'
    main.cpp:(.text+0x1b): undefined reference to `refresh'
    main.cpp:(.text+0x20): undefined reference to `stdscr'
    main.cpp:(.text+0x28): undefined reference to `wgetch'
    main.cpp:(.text+0x2d): undefined reference to `endwin'
    collect2: ld returned 1 exit status
    make: *** [main] Error 1
    

我是不是漏掉了什么?

链接器按照指定的顺序处理参数,跟踪前面参数中未解析的符号,并在后面的参数中找到它们时解析它们。这意味着 -lncurses 参数(定义符号)必须 遵循 main.o 参数(引用它们)。

在您的 Makefile 中,更改为:

main: $(OBJS)
    g++ -lncurses $^ -o $@

对此:

main: $(OBJS)
    g++ $^ -lncurses -o $@