Search code examples
c++linuxncursescurses

ncurses doesn't work with -lncurses


I try to use ncurses library in Ubuntu 12.04 LTS. It doesn't work. I go to step by step:

  1. Install:

    
    sudo apt-get update
    sudo apt-get install libncurses-dev
    

  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, add -lncurses to link and compile:

    
    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
    

  4. build (get error):

    $ 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
    

Did I miss something?


Solution

  • The linker processes arguments in the order they're specified, keeping track of unresolved symbols in earlier arguments and resolving them as they're found in later arguments. Which means that the -lncurses argument (which defines the symbols) has to follow the main.o argument (which refers to them).

    In your Makefile, change this:

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

    to this:

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