Check C++ random is working with CMake

The C++ STL <random> header may not be implemented correctly by some C++ compiler / CPU arch platforms. If a function using <random> is not essential to the program, avoid build errors by checking that <random> is working at configure time. This example checks that <random> is working with CMake.

include(CheckSourceCompiles)

check_source_compiles(CXX
"#include <random>
int main(){
  std::mt19937 mt_rand(0);
  return 0;
}"
HAVE_MERSENNE_TWISTER
)

add_executable(main main.cpp)
target_compile_definitions(main PRIVATE $<$<BOOL:${HAVE_MERSENNE_TWISTER}>:HAVE_MERSENNE_TWISTER>)

The “main.cpp” can have #ifdef HAVE_MERSENNE_TWISTER to conditionally compile code that uses <random>. This allows the rest of the program that doesn’t use this function to work without <random> or to fallback to a simpler RNG if suitable.

#ifdef HAVE_MERSENNE_TWISTER
#include <random>
#endif

#include <cstdlib>
#include <iostream>

void init_rand(){
#ifdef HAVE_MERSENNE_TWISTER
  std::mt19937 mt_rand(0);
#else
  std::cerr << "Warning: mt19937 not available\n";
#endif
}