-1

I need to share some variables among different source files. Now I use namespace like below, which seems a little odd. Adding const may be better, but the global variables will be assigned by loading configure file together not one for one time. So the initializer_list can't be used. Is there any better solution for it?

// configuration.hpp
#include <string>

namespace configuration {

  extern int ni;
  extern int nk;
  extern int nt;
  extern double dt;

  extern std::string grid_config_file;
  extern std::string media_config_file;
  extern std::string source_config_file;

  void SetConfiguration(const std::string &);
};

// configuration.cc
#include "configuration.hpp"
#include <string>
#include <yaml-cpp/yaml.h>

namespace configuration {
  int ni;
  int nk;
  int nt;
  double dt;

  std::string grid_config_file;
  std::string media_config_file;
  std::string source_config_file;

  void SetConfiguration(const std::string &main_config) {
    YAML::Node config = YAML::LoadFile(main_config);

    YAML::Node conf_basic = config["conf_basic"];
    ni = conf_basic["ni"].as<int>();
    nk = conf_basic["nk"].as<int>();
    nt = conf_basic["nt"].as<int>();
    dt = conf_basic["dt"].as<double>();

    YAML::Node conf_file = config["conf_file"];
    grid_config_file = conf_file["grid_conf"].as<std::string>();
    media_config_file = conf_file["media_conf"].as<std::string>();
    source_config_file = conf_file["source_conf"].as<std::string>();
  }

}

The configure file(conf.yaml)

---
# The basic parameters
conf_basic:
  ni: 100
  nk: 100
  nt: 200
  dt: 0.1

# The detailed configure files
conf_file:
  grid_conf: Grid.yaml
  media_conf: Media.yaml
  source_conf: Source.yaml
Aristotle0
  • 317
  • 2
  • 9

1 Answers1

0

Please take a look at Singleton design pattern. You can wrap the variables inside a public class and access them through a static method. At the first access you initialize the variables from whereever you need.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76
  • You mean it can be done like http://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289. When I need these global variables in some function, I just add `Configuration conf = Configuration.getInstance(); int ni = conf.ni;` in the function, is it right? – Aristotle0 Jul 17 '16 at 10:19
  • @Aristotle0 yes, I suggest you also to learn about this disign pattern, as you are going to use it, but is one of the simplest. It consist in when you need for the first time the object, then you instantiate, and you keep using the same object always. This way you can keep the values inside your object, and create getters for that values. – meJustAndrew Jul 17 '16 at 10:31