2

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.

5
  • 4
    You should get rid of those global variables altogether. Pass rand generator to the function requiring it as an argument. Commented Jan 26, 2018 at 17:14
  • 2
    You can declare variables without defining them with the extern keyword. Commented Jan 26, 2018 at 17:30
  • 1
    In main.cpp, before you #include the header file, put a #define MAIN but don't #define MAIN in your other translation units. Then inside your include file, if MAIN is defined, declare your random generators, whereas if MAIN is not defined, precede the random generators with extern. Commented Jan 26, 2018 at 19:13
  • Your comments brought me to 2 solutions: passing a function pointer around to the functions that need it, and another one using "extern". Now I just need to decide which one is better, but it's a lot cleaner than duplicate code. Thank you @ everyone Commented Jan 26, 2018 at 20:13
  • 1
    You should never include a cpp file from another one. Only header files should ever be shared. Commented Jan 28, 2018 at 1:41

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.