简体   繁体   English

`clear` 导致未定义的引用错误

[英]`clear` causes undefined reference error

I'm don't seem to be able to generate random number in C under Ubuntu 12.04 .我似乎无法在Ubuntu 12.04下用C生成随机数。

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".我将文件命名为“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 ?以及如何在Ubuntu 12.04使用gccC生成随机数?

Thanks in advance!提前致谢!

This has nothing to do with random numbers.这与随机数无关。 The problem is that you're linking without the curses library.问题是您在没有curses库的情况下进行链接。

You need to add -lncurses to your gcc command line:您需要将-lncurses添加到您的gcc命令行:

 $ 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));使用srand(time(0)); before calling rand() .在调用rand()之前。

Use srand ( time(NULL) );使用srand ( time(NULL) ); before number = rand() % 2;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.删除clear()并使用getchar()而不是getch() ,然后它应该可以正常工作。

  • getch() is used in compilers that support un-buffered input, but in case of gcc it's buffered input so use getchar() . getch()用于支持非缓冲输入的编译器,但在 gcc 的情况下它是缓冲输入,所以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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