0

I am trying to define static members in a class and always received error undefined reference to static members.

I realize there are already many similar questions. But It seems that in those questions errors are raised because they did not define static members somewhere outside the class. I am sure that I have defined these static members.

The following is the problematic part of my code.

In foo.h, I defined a class named foo.

#include <random>
#include <vector>
class foo
{
public:
int random = dist(mt);
static std::random_device rd;
static std::mt19937 mt;
static std::uniform_int_distribution<int> dist;
static std::vector<int> ans(const int &);
};

In foo.cpp, there are definitions of static members.

#include<random>
#include<vector>
#include "foo.h"
std::random_device foo::rd;
std::uniform_int_distribution<int> foo::dist(0, 10);
std::mt19937 foo::mt(rd());
std::vector<int> foo::ans(const int & size) {
    std::vector<int> bb;
    for(int i=0; i < size; ++i)
        bb.push_back(dist(mt));
    return bb;
}

I used the class in another cpp file named test.cpp

#include <random>
#include <vector>
#include <iostream>
#include "foo.h"
int main()
{
    foo a;
    std::vector<int> c=a.ans(5);
    for(auto it=c.begin(); it!=c.end(); ++it)
            std::cout<<*it<<"\t";
    std::cout<<"\n";
}

With g++ test.cpp -o a.out, I always received:

/tmp/ccUPnAxJ.o: In function `main':
test.cpp:(.text+0x37): undefined reference to `foo::ans(int const&)' 
/tmp/ccUPnAxJ.o: In function `foo::foo()':
test.cpp:(.text._ZN3fooC2Ev[_ZN3fooC5Ev]+0xd): undefined reference to `foo::mt'
test.cpp:(.text._ZN3fooC2Ev[_ZN3fooC5Ev]+0x12): undefined reference to `foo::dist'
collect2: error: ld returned 1 exit status' 

My g++ version is: g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2, and g++ is an alias to g++ -std=c++11.

1

1 Answer 1

1

You need:

g++ test.cpp foo.cpp -o a.out

Otherwise, how would g++ know about foo.cpp at all? It doesn't magically guess based on seeing #include "foo.h".

1
  • Well, I thought it would do this automatically. I misunderstood it. Thanks.
    – user41363
    Commented Jan 12, 2015 at 9:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.