CoderApprentice
CoderApprentice

Reputation: 455

How to use the same random number generator among different C++ files

I am running EDAC algorithms in my main.cpp file. So I linked it with hamming.cpp, hadamard.cpp and reedsolomon.cpp. To test the performance of these algorithms, I am generating random numbers in each file separately. So in each file, this code is at the top:

/**
 * Random number generator functionality
 **/
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 eng(seed);

std::uniform_int_distribution<> dist{1, 2000000};

Of course, we get a duplicate symbol error. So I wanted to dirty fix this at first by just changing the names of all the variables slighty, but essentially I'd have a lot of duplicate code.

I'm aware of header files and I am using them for all my .cpp files. However as far as I understand, you only use header files to declare functions and classes so the compiler knows what it is going to come across beforehand.

I also tried putting this piece of code in a randomnrgen.cpp file and then adding

#include randomnrgen.cpp

above each of the files that needed it, but that gave me the same duplicate errors. I am using the header guard trick by the way:

#ifndef INCLUDE_GUARD_H
#define INCLUDE_GUARD_H

#include "hamming.h"

#endif

So I was wondering if there is an elegant alternative solution to my dirty fix proposal? I need to access the "dist()" function with input "eng" in all of my files, so I need access to them but only want to declare them somewhere once.

Upvotes: 2

Views: 896

Answers (1)

Marine Galantin
Marine Galantin

Reputation: 2279

It is okay to have global random number generator.

See:

  1. Using same random number generator across multiple functions,

  2. RNGs and global variable avoidance.

And if you are looking for how to do it:

How do I use extern to share variables between source files?

Upvotes: 3

Related Questions