I've written a simple RNG class in C++ for use in a project:
/* Copyright (c) 2012 Fredrik Wikstrom */ #include "types.h" #include <cassert> namespace Game { typedef uint32_t random_T; typedef int32_t srandom_T; const int RNG_J = 31; const int RNG_K = 55; const random_T RNG_MAX = 0xffffffff; class RNG_State { public: random_T v[RNG_K+1]; random_T x, j, k; bool init; RNG_State() : init(false) { } }; class RNG { private: static RNG_State m_state; public: static void Seed(random_T seed) { int i; m_state.v[0] = seed; for (i = 1; i <= RNG_K; i++) { m_state.v[i] = 3 * m_state.v[i-1] + 257; } m_state.x = RNG_K; m_state.j = RNG_K-RNG_J; m_state.k = 0; m_state.init = true; } static random_T Rand() { random_T rand; assert(m_state.init); rand = m_state.v[m_state.j] * m_state.v[m_state.k]; m_state.x = (m_state.x + 1) % (RNG_K+1); m_state.j = (m_state.j + 1) % (RNG_K+1); m_state.k = (m_state.k + 1) % (RNG_K+1); m_state.v[m_state.x] = rand; return rand; } static random_T RandMax(random_T max) { assert(max > 0); return Rand() / (RNG_MAX / (max + 1)); } static srandom_T RandRange(srandom_T min, srandom_T max) { assert(max > min); return min + RandMax(max - min); } static random_T RandChance(random_T a, random_T b) { assert(b > 0); return RandMax(b - 1) < a; } }; }
It's supposed to be usable without having an object so all methods are declared as static and the one structure that is used to store state data is declared as a static too but still when I compile and link my code it generates undefined references to the m_state member:
$ make
g++ -O2 -Wall -std=c++0x -Iinclude -c -o main.o main.cpp
g++ -o game main.o -lcurses
main.o: In function `main':
main.cpp:(.text.startup+0xa0): undefined reference to `Game::RNG::m_state'
main.cpp:(.text.startup+0xab): undefined reference to `Game::RNG::m_state'
main.cpp:(.text.startup+0xb9): undefined reference to `Game::RNG::m_state'
main.cpp:(.text.startup+0xcc): undefined reference to `Game::RNG::m_state'
main.cpp:(.text.startup+0xd6): undefined reference to `Game::RNG::m_state'
main.o:main.cpp:(.text.startup+0xe0): more undefined references to `Game::RNG::m_state' follow
collect2: ld returned 1 exit status
make: *** [game] Error 1
Maybe someone who is more experienced than me with C++ can explain what is going on here and how I should fix this?
Found the solution after googling around for a bit. Apparently I have to create a .cpp file with the actual variable definition in it and then compile and link it to my program for this to work.