简体   繁体   中英

`clear` causes undefined reference error

I'm don't seem to be able to generate random number in C under Ubuntu 12.04 .

I wrote the fallowing code:

#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main (int argc,char* argv[])
{
     int number;
     clear();

     number = rand() % 2; // want to get only 0 or 1

     printf("%d",number);
     getch();
     return 0;
}

I named the file "test_gcc.c".

After that I compile it with:

$ sudo gcc -o test_gcc test_gcc.c

And i get the following message:

/tmp/ccT0s12v.o: In function `main':
test_gcc.c:(.text+0xa): undefined reference to `stdscr'
test_gcc.c:(.text+0x12): undefined reference to `wclear'
test_gcc.c:(.text+0x44): undefined reference to `stdscr'
test_gcc.c:(.text+0x4c): undefined reference to `wgetch'
collect2: ld returned 1 exit status

Can somebody tell me what did I do wrong?

And also how to generate random number in C on Ubuntu 12.04 using gcc ?

Thanks in advance!

This has nothing to do with random numbers. The problem is that you're linking without the curses library.

You need to add -lncurses to your gcc command line:

 $ gcc -o test_file test_file.c -lncurses

You didn't seed the random number generator. <-- Not the reason for errors

Use srand(time(0)); before calling rand() .

Use srand ( time(NULL) ); before number = rand() % 2; to get different random number every time the executable is ran.

For errors:

  • remove clear() and use getchar() instead of getch() and then it should worked fine.

  • getch() is used in compilers that support un-buffered input, but in case of gcc it's buffered input so use getchar() .

code:

#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main (int argc,char* argv[])
{
    int number;
    srand(time(NULL));
    number = rand() % 2; // want to get only 0 or 1
    printf("%d",number);
    getchar();
    return 0;
}

尝试 :

 gcc -o test_gcc test_gcc.c -lncurses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM