Jack Hermanson
Jack Hermanson

Reputation: 71

How can I access a public static int variable in another class/file?

The IDE I am using is Microsoft Visual Studio 2022 and I am following a guide for game development.

I have the following code:

//Game.h
#pramga once
class Game{
public:
    Game();
    static int mapWidth;
};

//Game.cpp
#include "Game.h"

//Initialization
int Game::mapWidth;

//Implementation class
Game::Game(){
mapWidth = 10;
};

//Camera.h
#pragma once
#include "Game.h"

class Camera{
    Camera() = default;
    void update(){
      if (Game::mapWidth > 0)
          //do something
    }
};

What is interesting is that if I hover over this variable in Camera.h the IDE recognizes the variable and where its coming from. But, when i go to compile i get the following error from my if statement:

C2653 'Game': is not a class or namespace name

I am using the scope resolution operator and my vairable is public static and initialized in Game.cpp/h. So, why am I getting this compile error when the IDE recognizes the variable and the Game class as existing?

Upvotes: 0

Views: 88

Answers (1)

Sup3rlum
Sup3rlum

Reputation: 121

You seem to be missing a trailing semicolon at the end of your Game class definition. Definitions of structs and classes in C++, unlike in other languages, end in closing bracket AND a semicolon. Such an error might be hard to spot (depending on your IDE). When the preprocessor includes Game.h in Game.cpp, it puts it right above the initialization of Game::mapWidth, which causes it to get invalidated.

Proper definition should like this:

class Game {
public:
    static int mapWidth;
    Game(); // <-- declaration of constructor should be here 
}; // <-- note the semicolon

This is the case for your Camera class as well.

class Camera{
    if (Game::mapWidth > 0)
         //do something
}; // Semicolon

Upvotes: 1

Related Questions