Onedayitwillmake
Onedayitwillmake

Reputation: 711

Static variables used as constants return zero in other class

I have a class that I'm using to store some static default variables for a visual experiment I'm creating.

They are not marked as const, because Im using a GUI to tweak them at runtime. When I log them in the main class ( which calls the static function init on the Defaults class ) - they are valid. But in the constructor of the different class it returns zero.

The output looks like this

"Constants::init() called" // Constants::Heads::MIN_LIFETIME initialized to 1200
preSetup-Log  Constants::Heads::MIN_LIFETIME 1200
PhysicsObject- Constants::Heads::MIN_LIFETIME 0 // Y you zero?
postSetup-Log  Constants::Heads::MIN_LIFETIME 1200

I'm defining the constants like this:

namespace Constants {
    namespace Forces {
        static int MAX_LIFETIME;
        static float GRAVITY_FORCE;
    };
}


static void init() {
    std::cout << "Constants::init()" << std::endl;
    Constants::Forces::GRAVITY_FORCE = 40000.0f;
    Constants::Forces::MAX_LIFETIME = 3000;
}

Upvotes: 1

Views: 124

Answers (2)

JohnPS
JohnPS

Reputation: 2626

// header.h
namespace Constants {
    namespace Forces {
    extern int MAX_LIFETIME;
    extern float GRAVITY_FORCE;
    }
}

// my_constants.cpp
namespace Constants {
    namespace Forces {
        int MAX_LIFETIME = 3000;
        float GRAVITY_FORCE = 40000.0f;
     }
}

Then include header.h in a file that uses the constants. The constants will be initialized automatically when the program starts.

Upvotes: 3

iammilind
iammilind

Reputation: 70030

This is because when you declare a variable static inside a (say .h) file and include that file in various .cpp files then for every .cpp file (translation unit), a separate copy of the variable is created. For example,

// x.h ...
    namespace Forces {
        static int MAX_LIFETIME;  // unique copy for each translation unit (.cpp)
        static float GRAVITY_FORCE;  // same as above

        extern int SOMETHING; //<----- creates only single copy 
    };

As shown, you should create the variable as extern inside the namespace and define that variable in only one of the .cpp files.

Other way is to enclose them inside a class instead of namespace:

class Forces {
    static int MAX_LIFETIME;  // only 1 copy
    static float GRAVITY_FORCE;  // only 1 copy
};

You still have to define them in one of the .cpp files as,

int Forces::MAX_LIFETIME = <>;

Upvotes: 4

Related Questions