Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 416
JDH Avatar asked Apr 23 '12 05:04

JDH


People also ask

Is it OK to use global variables in C?

Master C and Embedded C Programming- Learn as you go Non-const global variables are evil because their value can be changed by any function. Using global variables reduces the modularity and flexibility of the program. It is suggested not to use global variables in the program.

Can global variables be used anywhere?

You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.

Is it better to use more number of global variables as they can be accessed from different routines?

It is seldom advisable to use Global variables as they are liable to cause bugs, waste memory and can be hard to follow when tracing code. If you declare a global variable it will continue to use memory whilst a program is running even if you no longer need/use it.

What can I use instead of global variables in C?

Use Local Variables Instead The idea is that the global variable gState is replaced by the local variable sState in the script of your main application stack. All references to the variable in the application can be replaced with calls to either setState or getState.


1 Answers

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.

like image 112
iammilind Avatar answered Sep 19 '22 10:09

iammilind