0

I can get the mt19937 rng seeded in a simple app. Now I am trying to get it seeded once per app and use it multiple times whenever it's needed. Here is my code. The error I'm getting is in GenerateRandomNumber - "gen: undeclared identifier".

main.cpp

#include <iostream>
#include "general.h"

int main() {

CallOncePerApp();

// Loop for output testing
// Ultimately, GenerateRandomNumber can be called from anywhere in any CPP file
for (int i=0;i<10;i++)  {
    int dwGen = GenerateRandomNumber(1, 1000);
    cout << dwGen; // print the raw output of the generator.
    cout << endl;
    }
}

general.h:

#include <random>

using namespace std;

extern random_device rd;
extern void CallOncePerApp();
extern mt19937 gen;

extern unsigned int GenerateRandomNumber(unsigned int dwMin, unsigned int dwMax);

general.cpp:

#include <random>

using namespace std;
random_device rd;
mt19937 gen;

void CallOncePerApp() 
{
    // Error C2064 term does not evaluate to a function taking 1 arguments
    gen(rd); // Perform the seed once per app
}

unsigned int GenerateRandomNumber(unsigned int dwMin, unsigned int dwMax) 
{
    uniform_int_distribution <int> dist(dwMin, dwMax); // distribute results between dwMin and dwMax inclusive.
    return dist(gen);
}
JeffR
  • 765
  • 2
  • 8
  • 23

1 Answers1

0

Here,

mt19937 gen; // gen is an object of class mt19937! not a function

void CallOncePerApp() 
{
    // Error C2064 term does not evaluate to a function taking 1 arguments
    gen(rd); // **** therefore this line is wrong!
}

Also you need to include the header file in "general.cpp" file.

CS Pei
  • 10,869
  • 1
  • 27
  • 46
  • Oh, forgot the header file. So what does the general.cpp file look like? That code gives an error as you said. What do I put in CallOncePerApp? I need it to be thread-safe, so I need 'thread_local' somewhere. – JeffR Mar 24 '19 at 13:50
  • Not sure about the whole structure and design. But I would not make `mt19937 gen` a global variable if you concerns about thread safety. – CS Pei Mar 24 '19 at 15:14
  • Is it the right answer, @JeffR ? – DanielTuzes Oct 27 '21 at 22:51