c ++未定义的静态变量引用

时间:2012-08-24 23:26:32

标签: c++ reference linker sdl undefined

我不知道为什么这段代码不起作用。所有的源文件都编译好了,但是当我尝试链接它们时,编译器会因为未定义的引用错误而对我大喊大叫。这是代码:

main.cpp中:

#include "SDL/SDL.h"
#include "Initilize.cpp"

int main(int argc, char* args[]) 
{
    //Keeps the program looping
    bool quit = false;
    SDL_Event exit;
    //Initilizes, checks for errors
    if(Initilize::Start() == -1) 
    {
        SDL_Quit();
    }
    //main program loop
    while(quit == false) 
    {
        //checks for events
        while(SDL_PollEvent(&exit)) 
        {
            //checks for type of event;
            switch(exit.type) 
            {
                case SDL_QUIT:
                quit = true;
                break;
            }
        }
    }
    return 0;
}

Initilize.h:

#ifndef INITILIZE_H
#define INITILIZE_H
#include "SDL/SDL.h"

/* Declares surface screen, its attributes, and Start(); */
class Initilize {
protected:
    static SDL_Surface* screen;
private:
    static int SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP;
public:
    static int Start();
};

#endif

Initilize.cpp:

#include "Initilize.h"
#include "SDL/SDL.h"

/* Initilizes SDL subsystems, sets the screen, and checks for errors */
int Initilize::Start() 
{
    //screen attributes
    SCREEN_WIDTH = 640;
    SCREEN_HEIGHT = 480;
    //Bits per pixel
    SCREEN_BPP = 32;
    //Inits all subsystems, if there's an error, return 1   
    if(SDL_Init(SDL_INIT_EVERYTHING) == -1) {
            return 1;
    }
    //sets screen
    screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);
    //Returns 1 if there was in error with setting the screen
    if(screen == NULL) {
            return 1;
    }
    SDL_WM_SetCaption("Game", NULL);
    return 0;
}

很抱歉,如果代码格式化很奇怪,插入四个空格放入一个代码块就会搞砸了。

3 个答案:

答案 0 :(得分:16)

将以下内容添加到您的cpp文件中:

SDL_Surface* Initilize::screen = 0; // or nullptr
int Initilize::SCREEN_WIDTH = 640;
int Initilize::SCREEN_HEIGHT = 480;
int Initilize::SCREEN_BPP = 32;

此外,如果这些值永远不会改变,那么最好使它们成为const。您需要将上述内容添加到cpp文件中的原因是因为需要在类外部定义静态成员变量。你班级中的static SDL_Surface* screen;等只是 一个声明,而不是一个定义。 static成员被认为是特殊的,与全局变量非常相似。

原因是因为静态成员在您的类的所有实例之间共享。这意味着它们只能被定义为一次并且允许类中的定义会导致多个定义发生,因此C ++标准强制您在类之外定义它(并且还暗示您应该将它定义为在cpp文件中定义。)

答案 1 :(得分:2)

Initialize.cpp

#include "Initialize.h"
#include "SDL/SDL.h"

// this is the new line to insert
SDL_Surface* Initialize::screen = 0;
int Initialize::SCREEN_WIDTH=...; // whatever you want to set it to
int Initialize::SCREEN_HEIGHT=...; // whatever you want to set it to
int Initialize::SCREEN_BPP=...; // whatever you want to set it to

并删除main.cpp中的#include "Initialize.cpp"

代替

#include "Initialize.hpp"

如果您正在使用gcc,请使用

进行编译
g++ -o <output-file> main.cpp Initialize.cpp <include flags like -I> <lib flags like -L>

答案 2 :(得分:1)

您似乎从未初步化过您的视觉效果。您是在Initialize start方法中分配它们但没有初始化它们。尝试添加int SCREENWIDTH;之前,在源文件中分配它,而不仅仅是头文件