[英]`clear` causes undefined reference error
我似乎无法在Ubuntu 12.04
下用C
生成随机数。
我写了闲置的代码:
#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;
}
我将文件命名为“test_gcc.c”。
之后我编译它:
$ sudo gcc -o test_gcc test_gcc.c
我收到以下消息:
/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
有人能告诉我我做错了什么吗?
以及如何在Ubuntu 12.04
使用gcc
在C
生成随机数?
提前致谢!
这与随机数无关。 问题是您在没有curses
库的情况下进行链接。
您需要将-lncurses
添加到您的gcc
命令行:
$ gcc -o test_file test_file.c -lncurses
您没有为随机数生成器设置种子。 <-- 不是错误的原因
使用srand(time(0));
在调用rand()
之前。
使用srand ( time(NULL) );
在number = rand() % 2;
每次运行可执行文件时获取不同的随机数。
对于错误:
删除clear()
并使用getchar()
而不是getch()
,然后它应该可以正常工作。
getch()
用于支持非缓冲输入的编译器,但在 gcc 的情况下它是缓冲输入,所以使用getchar()
。
代码:
#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.