Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++11 static functional member variable

Tags:

c++

static

c++11

Well, I'm stumped. I've always had a bit of a hard time with static member variables and functions, so if the answer to this is really obvious, I apologize. I can't figure out what's wrong, though.

In WSGrid.h:

#include <functional>

class WSGrid
{
public:
    //constructors...

    static const std::function< char( void ) > _randomChar;

    //private data...
};

In WSGrid.cpp:

#include <random>

std::default_random_engine generator;
std::uniform_int_distribution< char > distribution;

const WSGrid::_randomChar = std::bind( distribution, generator );

In my main.cpp:

#include "WSGrid.h"
#include <iostream>

int main( int argc, char* argv[] )
{
    std::cout << WSGrid::_randomChar() << std::endl;
    return 0;
}

And when I try to compile (g++ -std=c++11 -Wall -pedantic main.cpp), I get "undefined reference to WSGrid::_randomChar".

So... it looks, to me, like I'm doing everything right. I'm following the syntax found here, at least as far as I'm aware. But apparently there's something wrong.

like image 801
Arandur Avatar asked Apr 30 '26 00:04

Arandur


1 Answers

You need to define _randomChar correctly.

update :

const WSGrid::_randomChar = std::bind( distribution, generator );

to:

const std::function<char(void)> WSGrid::_randomChar = std::bind(distribution, generator);

Also you need to link WSGrid.cpp

g++ -std=c++11 -Wall -pedantic -c WSGrid.cpp -o WSGrid.o
g++ -std=c++11 -Wall -pedantic main.cpp WSGrid.o
like image 145
billz Avatar answered May 01 '26 13:05

billz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!