Mike ODell
Mike ODell

Reputation: 37

Create a box in C Program with Curses

I am trying to create a box with a game inside the box, but for now I am using the text this is my box for testing. I am very confusing with curses for first time but I am trying to learn for myself in my spare time. I do not have any problems with other C program before but this time, I keep getting the message error after when I compile on Repl.it, but #include <windows.h> does not existing in the system file or on the Linux system too.

#include <stdio.h>
#include <ncurses.h>
#include <stdlib.h>

int main(int argc, char ** argv){

  initscr();
  int height, width, start_y, start_x;
  height = 10;
  width = 20;
  start_y = start_x = 10;

  WINDOW * win = newwin(height, width, start_y, start_x);
  refresh();

  box(win, 0, 0);
  mvwprintw(win, 1, 1, "this is my box");
  wrefresh(win);

  int c = getch();

  endwin();



return 0;
}

Error Messages:

gcc version 4.6.3
exit status 1
/tmp/cc3HSdBS.o: In function `main':
main.c:(.text+0x10): undefined reference to `initscr'
main.c:(.text+0x3e): undefined reference to `newwin'
main.c:(.text+0x49): undefined reference to `stdscr'
main.c:(.text+0x51): undefined reference to `wrefresh'
main.c:(.text+0x82): undefined reference to `wborder'
main.c:(.text+0xa6): undefined reference to `mvwprintw'
main.c:(.text+0xb2): undefined reference to `wrefresh'
main.c:(.text+0xb9): undefined reference to `stdscr'
main.c:(.text+0xc1): undefined reference to `wgetch'
main.c:(.text+0xc9): undefined reference to `endwin'
collect2: error: ld returned 1 exit status

Compiled with:

g++ -Incurses project.c -o project

Upvotes: 0

Views: 2453

Answers (1)

ad absurdum
ad absurdum

Reputation: 21367

You have to pass a linker flag to the compiler so that the ncurses library is linked at compile time. This flag is -lncurses.

From comments made by OP, the compiler invocation was:

g++ -Incurses project.c -o project

The initial l (ell) was mistakenly made into an I in the linker flag (an easy mistake to make). Further, the linker flag is in the wrong position in this invocation. Linker flags must follow their source files. A better invocation would be:

g++ -o project project.c -lncurses

I am not sure why OP is using g++ here for C code; it might be better to use gcc directly. I would additionally suggest always enabling some warnings:

gcc -std=c11 -Wall -Wextra -Wpedantic -o project project.c -lncurses

Upvotes: 2

Related Questions