因此,我正在尝试创建一个伪随机数生成器,它将返回指定范围内的 RN,以便稍后在我的程序中使用。
不幸的是,我的编译器 (gcc) 无法识别类型“time_t”、函数“time()”等。我以为我已经包含了正确的 header - 但仍然存在编译错误。我可能只是累了,但谷歌搜索错误并没有得到有用的信息——所以我转向了很棒的 stackoverflow。如果问题很简单而我只是忽略了它,我深表歉意...
我的包含语句:
#include "param.h"
#include "mmu.h"
#include "x86.h"
#include "proc.h"
#include "spinlock.h"
#include "pstat.h"
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
RNG:
static int random_range (unsigned int min, unsigned int max){
// Get value from system clock and place in seconds variable
time_t seconds;
// Convert seconds to a unsigned integer.
time(&seconds);
// Set seed
srand((unsigned int) seconds);
int base_r = rand();
if (RAND_MAX == base_r) return random_range(min, max);
// now guaranteed to be in [0, RAND_MAX)
int range = max - min,
int remainder = RAND_MAX % range,
int bucket = RAND_MAX / range;
// There are range buckets, plus one smaller interval within remainder of RAND_MAX
if (base_random < RAND_MAX - remainder) {
return min + base_random/bucket;
}
else return random_in_range (min, max);
}
与上述相关的编译器错误 - 并非全部,因为我确定我遗漏了一些包含语句或类似语句:
kernel/proc.c:9:18: error: time.h: No such file or directory
kernel/proc.c:10:20: error: stdlib.h: No such file or directory
kernel/proc.c:11:19: error: stdio.h: No such file or directory
kernel/proc.c: In function ‘random_range’:
kernel/proc.c:31: error: ‘time_t’ undeclared (first use in this function)
kernel/proc.c:31: error: (Each undeclared identifier is reported only once
kernel/proc.c:31: error: for each function it appears in.)
kernel/proc.c:31: error: expected ‘;’ before ‘seconds’
最佳答案
您正在编译文件:
kernel/proc.c
所以您显然是在内核中工作。您可能没有意识到这一点,但是标准库不存在 并且无法编译到内核中。
stdio.h
, stdlib.h
, 和 time.h
在内核开发环境中不存在,所以这就是你得到错误的原因。
你需要#include <linux/time.h>
对于时间的东西......并不是说它对你有多大帮助,因为正如你所说,rand()
函数集在内核中不起作用。
现在,如果您包括 #include <linux/random.h>
然后你可以使用
void get_random_bytes(void *buf, int nbytes);
该接口(interface)将返回请求的随机字节数并将其放入缓冲区。你可以如此有效地做到:
int i;
get_random_bytes(&i, sizeof i);
如果您看到条目 /dev/random
或 /dev/urandom
,这是该文件系统条目的内核端。
关于c - C 中的伪随机数生成器 - 使用时间函数播种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21964508/