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.
externkeyword.main.cpp, before you #include the header file, put a#define MAINbut don't#define MAINin 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 withextern.