JDH
JDH

Reputation: 63

C++ input global variables accessible across several classes

I'm developing a project that takes several command-line arguments, and uses these as parameters for subsequent simulations. (I want to run a large number of experiments in a batch).

What's the best way to set global variables at runtime? Global in terms of: the variables may change in the duration of a run, but should be accessible across a large number of classes.

Currently I read them into a Config object which I include in other classes. If anyone has better ideas (xml?) I'm all ears.

Thanks!

Upvotes: 6

Views: 2644

Answers (1)

iammilind
iammilind

Reputation: 70000

Bring all the related variables under one roof for ease of access. 2 approaches are possible:

(1) Namespace globals

namespace Configuration {
  extern int i;
  extern bool b;
  extern std::string s;
}

(2) Class static members

class Configuration {  // provide proper access specifier
  static int i;
  static bool b;
  static std::string s;
}

To track them nicely, use getter()-setter() methods as wrapper inside namespace/class.
With getters-setters you can handle them in a thread-safe way, if the program demands.

Upvotes: 8

Related Questions