I'm trying to write a multi-file program including the following code related to random number generation:
in help.h file:
extern random_device rand_dev;
extern ranlux48 rand_eng;
extern uniform_real_distribution<> zero2one_dist;
in help.cpp file:
#include "help.h"
random_device rand_dev;
ranlux48 rand_eng{ rand_dev() };
uniform_real_distribution<> zero2one_dist(0, 1);
in main.cpp file
#include "help.h"
//identical as help.cpp, just for illustration of the problem
random_device rand_dev1;
ranlux48 rand_eng1{ rand_dev1() };
uniform_real_distribution<> zero2one_dist1(0, 1);
//random number generation
float rnd1 = zero2one_dist1(rand_eng1);
float rnd2 = zero2one_dist(rand_eng);
//main function
int main()
{
//another random number generation.
float rnd3 = zero2one_dist(rand_eng);
//output
cout << rnd1 << endl << rnd2 << endl << rnd3 << endl;
return 0;
}
The desired result is outputting three random number between 0 and 1, however, rnd1
and rnd3
generates proper result but rnd2
keeps 0?!
I'm totally confused here, what's the difference between definitions in external file help.h and in main.cpp and what's the difference between a call inside and outside main()?
In my real work, I would need to write the code in the form of rnd2
, but now it won't work and I don't know why.
Can anyone illustrate the difference between rnd1
, rnd2
and rnd3
and get rnd2
to work? Thanks!