LNK2001 error when accessing C ++ static variables

I try to use a static variable in my code when trying to use textures, however I keep getting this error:

1>Platform.obj : error LNK2001: unresolved external symbol "private: static unsigned int Platform::tex_plat" (?tex_plat@Platform@@0IA)

I correctly initialized the variable in the cpp file, however, I believe that this error occurs when trying to access it in another way.

.h

class Platform :
public Object
{
    public:
        Platform(void);
        ~Platform(void);
        Platform(GLfloat xCoordIn, GLfloat yCoordIn, GLfloat widthIn);
        void draw();
        static int loadTexture();

    private:
        static GLuint tex_plat;
};

.cpp classes: Here the variable is initialized

int Platform::loadTexture(){
 GLuint tex_plat = SOIL_load_OGL_texture(
            "platform.png",
            SOIL_LOAD_AUTO,
            SOIL_CREATE_NEW_ID,
            SOIL_FLAG_INVERT_Y
            );

    if( tex_plat > 0 )
    {
        glEnable( GL_TEXTURE_2D );
        return tex_plat;
    }
    else{
        return 0;
    }
}

Then I want to use the tex_plat value in this method:

void Platform::draw(){
    glBindTexture( GL_TEXTURE_2D, tex_plat );
    glColor3f(1.0,1.0,1.0);
    glBegin(GL_POLYGON);
    glVertex2f(xCoord,yCoord+1);//top left
    glVertex2f(xCoord+width,yCoord+1);//top right
    glVertex2f(xCoord+width,yCoord);//bottom right
    glVertex2f(xCoord,yCoord);//bottom left
    glEnd();
}

can someone explain this error.

+5
source share
2 answers

The static member must be defined outside the body class, so you need to add a definition and provide an initializer there:

class Platform :
public Object
{
    public:
        Platform(void);
        ~Platform(void);
        Platform(GLfloat xCoordIn, GLfloat yCoordIn, GLfloat widthIn);
        void draw();
        static int loadTexture();

    private:
        static GLuint tex_plat;
};

// in your source file
GLuint Platform::tex_plat=0; //initialization

It is also possible to initialize it inside your class, but:

, static const , .

+10

:

GLuint Platform::tex_plat;

.

0

All Articles