C 中的伪随机数生成器 - 具有时间函数的种子设定



所以我正在尝试创建一个伪随机数生成器,它将返回指定范围内的RN,以便稍后在我的程序中使用。

不幸的是,我的编译器(gcc)无法识别类型"time_t",函数"time()"等。我以为我已经包含了正确的标题 - 但仍然在编译时出错。我可能只是累了,但是谷歌搜索错误并没有产生有用的信息 - 所以我转向伟大的堆栈溢出。如果问题很简单,我只是忽略了它,我深表歉意......

我的包含语句:

#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.hstdlib.htime.h在内核开发的环境中不存在,所以这就是你得到错误的原因。

你需要#include <linux/time.h>时间的东西...并不是说它对您有很大帮助,因为正如您所说,rand()函数集在内核中不起作用。

现在,如果您包含#include <linux/random.h>那么您可以使用

void get_random_bytes(void  *buf, int nbytes);

此接口将返回请求的随机字节数并将其放置在缓冲区中。如此有效地,您可以做到:

int i;
get_random_bytes(&i, sizeof i);

如果您曾经看到过条目/dev/random/dev/urandom,这是该文件系统条目的内核端。

是的,你累了。请注意,您的编译器甚至似乎找不到<stdio.h>

kernel/proc.c:10:20: error: stdlib.h: No such file or directory

您需要尝试获取一个简单的"hello world"程序进行编译 - 现在编译器显然在错误的位置查找包含文件。您通常可以放置一个-I some/path来告诉编译器在哪里查找包含文件... 你能展示你的编译命令吗?

您拥有的生成文件是否有可能包含-nostdinc标志?这通常在编译内核代码时完成...请参阅 http://gcc.gnu.org/onlinedocs/cpp/Search-Path.html

啊...我想我明白了:

XV6 不能使用 stdlib 函数调用。我必须创建自己的随机函数。

有什么建议吗?请链接我...我知道有一种叫做"东西"的东西——扭曲者,应该是好的。

仅根据您发布的错误,很明显您的编译器找不到标准库头文件。这是问题的根源。

最新更新