Undefined reference when using ncurses on linux

2019-02-04 22:45发布

问题:

I'm trying to start developing a program using ncurses on Linux. I can't even get the Hello World example to compile. Here's the code:

#include <curses.h>

int main()
{         
        initscr();
        printw("Hello, world.");
        refresh();
        getch();
        endwin();
        return 0;
}

When I attempt to compile, I get:

hello.c:(.text+0x12): undefined reference to `initscr'

For every one of those called functions.

I installed ncurses via apt-get, and also by downloading the sources and compiling, installing, etc.

I have tried #include both curses.h and ncurses.h.

What is going on?

回答1:

Have you used the -lcurses option when linking?

Including the header files let the code compile (because the compiler knows what the function call looks like from the .h file), but the linker needs the library file to find the actual code to link into your program.



回答2:

As Greg Hewgill said, you need to pass in -lcurses or -lncurses to link to the curses library.

gcc -o hello hello.c -lncurses

You also probably mean to use initscr() and getch(). Once I make those substitutions, the above compiles for me.



回答3:

For anyone having similar problems: -lx arguments, where x is your library, should always follow the source and object files.



回答4:

I was having a similar issue and found a solution which helped me, but was slightly different from the other answers posted here. I was trying to use the panels library with curses and my compile command was:

$ gcc -o hello hello.c -lncurses -lpanel

when I read the other answers, I was baffled because I was including the -lncurses flag, but it still was not compiling, and with similar errors to what you were getting:

$ gcc -o hello hello.c -lncurses -lpanel
/usr/lib/gcc/i686-linux-gnu/4.7/../../../../lib/libpanel.a(p_new.o): In function `new_panel':
p_new.c:(.text+0x18): undefined reference to `_nc_panelhook'

I finally found my answer in the tldp:

"To use panels library functions, you have to include panel.h and to link the program with panels library the flag -lpanel should be added along with -lncurses in that order."

So, it appears that order is important when using the compile flags! I tried switching the order:

gcc -o hello hello.c -lpanel -lncurses

This allowed it to compile successfully. I know you already have your answer, so I hope this helps someone.



标签: c linux ncurses