Reputation: 23082
My program uses a Random
class which manages a generator type and provides templated functions to return distributions using the given generator. However, when I compile it I invariably get undefined reference errors.
To illustrate the problem I've created a simple program which contains a Random
class that simply provides a templated function Random::f()
which returns a normally distributed number:
#include <random>
#include <iostream>
class Random
{
public:
template <typename T>
static T f()
{
std::normal_distribution<T> distribution(0,1);
return distribution(generator);
}
static std::default_random_engine generator;
};
int main()
{
std::cout << Random::f<double>();
return 0;
}
When I compile this using gcc 4.9.2
I get:
quant@900AX:~/Documents$ echo $CC /usr/bin/gcc-4.9 quant@900AX:~/Documents$ $CXX -std=c++11 main.cpp /tmp/ccWCPiN7.o: In function `double Random::f<double>()': main.cpp:(.text._ZN6Random1fIdEET_v[_ZN6Random1fIdEET_v]+0x2b): undefined reference to `Random::generator' collect2: error: ld returned 1 exit status
Why am I getting this error?
Upvotes: 1
Views: 967
Reputation: 56479
Put the definition out of the class:
std::default_random_engine Random::generator;
The code you have written, just declares the member object, you have to write a definition for it.
Upvotes: 4
Reputation: 47794
Static data members declarations in the class declaration are not definition of them.
Provide a definition to generator
as its a static variable.
std::default_random_engine Random::generator = std::default_random_engine();
Upvotes: 3