3

I need to generate a random integer from a range and have found very interesting what is discussed here in the answer by @Walter. However, it is C++11 standard and I need to use C, is there a way of making the call from C? I reproduce his answer here:

#include <random>

std::random_device rd;     // only used once to initialise (seed) engine
std::mt19937 rng(rd());    // random-number engine used (Mersenne-Twister in this case)
std::uniform_int_distribution<int> uni(min,max); // guaranteed unbiased

auto random_integer = uni(rng);
Community
  • 1
  • 1
nopeva
  • 1,583
  • 5
  • 22
  • 38

3 Answers3

5

You cannot use C++ classes in C, but can wrap the C++ functionality in functions, which can be called from C, e.g. in getrandom.cxx:

#include <random>

static std::random_device rd;
static std::mt19937 rng(rd());
static std::uniform_int_distribution<int> uni(min,max);

extern "C" int get_random()
{
    return uni(rng);
}

This is a C++ module exporting a get_random function with C linkage (that is, callable from C. You declare it in getrandom.h:

extern "C" int get_random();

and can call it from your C code.

Martin Zabel
  • 3,589
  • 3
  • 19
  • 34
vbar
  • 251
  • 2
  • 8
  • I have written the `C++` code in a getrandom.cpp and created a getrandom.h file with the declaration. Then tried compiling `#include #include #include #include "getrandom.h" int main() { printf("%i\n", get_random()); } ` but it doesn't work, what I'm doing wrong? – nopeva Feb 27 '16 at 10:16
  • 1
    @AP13 There is semicolon missing at the end of the `get_random`'s declaration. Did you already fixed that? And do you get a compiler or runtime error? – Martin Zabel Feb 27 '16 at 15:11
  • @Martin Zabel thanks, yes I finally got it. The code was compiling fine but not linking well. – nopeva Feb 27 '16 at 19:03
3

If you want to call C++ code from C code, you can wrap your code in an extern "C" block. The function signature must be a valid C function, and is then available to C code to call. However, the contents of the function can include whatever C++-isms you want.

See this question for more info: In C++ source, what is the effect of extern "C"?

Community
  • 1
  • 1
Alex
  • 14,973
  • 13
  • 59
  • 94
1

Wrap it all up in a C++ function with extern "C" linkage.

Steve
  • 1,760
  • 10
  • 18