0

Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?

I have created this code

  class Game{
    static SDL_Surface* screen;
public:
    //Initiate Game(SDL_Graphics, folder for output.....) 
    static void initialize();
    static void initializeScreen();


};

void Game::initializeScreen()
{

    Game::screen = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 32,  SDL_DOUBLEBUF |SDL_HWSURFACE |SDL_SWSURFACE);
    SDL_Init(SDL_INIT_VIDEO);
    Game::screen == NULL ? printf("SDL_Init failed: %s\n", SDL_GetError()):printf("SDL_Init initialized\n");
    SDL_WM_SetCaption("SDL Animation", "SDL Animation");
}

It compiles but I get e linker error, how can I fix this?

1>game.obj : error LNK2001: unresolved external symbol "private: static struct SDL_Surface * Game::screen" (?screen@Game@@0PAUSDL_Surface@@A)

Edit: This is how I fixed it, in game.cpp added this

SDL_Surface* Game::screen;

outside of any function*

Community
  • 1
  • 1
Laggy
  • 58
  • 1
  • 10

2 Answers2

1

You need to add the following definition in your cpp file SDL_Surface* Game::screen = NULL.


Here is an example code where you can have a static variable without defining it in the cpp file using a function.

#include <iostream>

struct Lazy {
    static int& GetValue() {
        static int a = 0;
        return a;
    }
};

int main() {
    std::cout << Lazy::GetValue() << std::endl;
    int& a = Lazy::GetValue();
    a = 1;
    std::cout << Lazy::GetValue() << std::endl;
}
andre
  • 7,018
  • 4
  • 43
  • 75
1

You have to define static (variable) members (not functions) in seperate source files(*.cpp) and link against them.

for example:

//MyClass.h
class MyClass {
    static int x;
};

//MyClass.cpp
#include "MyClass.h"
int MyClass::x;
  • i get this error `error C2655: 'Game::screen' : definition or redeclaration illegal in current scope` – Laggy Nov 30 '12 at 15:02
  • 1
    thanks for help, I have figured it out, I tried to put it into the function initializeScreen() which didnt work, so I put it outside of the function and it worked :) – Laggy Nov 30 '12 at 15:43