How do I organize input global variables?

160 views Asked by At

In some spare time, I'm working on some physical simulation code so I a) have a framework to build off of in the future and b) keep myself fresh with C++. I have several values (speed of light, box size, number of particles, things like that) that very nearly every part of the program needs, but I'd really like to give the user the ability to specify these values in an input.cfg file (so things like #DEFINE+ a constants.h file won't work). I can certainly read these values in fine, but what's the conventional/best way to make them available across many different modules?

2

There are 2 answers

1
tadman On BEST ANSWER

Instead of a pile of otherwise unrelated global variables, why not make a struct or class to contain these and have a function that retrieves or updates the current state of the configuration?

For example, as a struct you could implement serialization methods to read from or write to a .cfg-type file.

That can also implement a static method to return the active configuration, so a global method that references a local variable in the implementation.

0
BeyelerStudios On

How about a singleton:

class Universe {
private:
     Universe();

public:
    static Universe& GetInstance();

    void Reload();

    double GetSpeedOfLight() const { return m_C; }
    ...

private:
    double m_C; //!< Speed of light
};

Universe& Universe::GetInstance() {
    static Universe instance;
    return instance;
}

Universe::Universe() {
    Reload();
}

void Universe::Reload() {
    // load your constants
}