0

I'm using boost::program_options in one of my applications. With it, I fill almost all of my classes parameters.

Since I need to pass "options" to different classes, I was declaring variable_map in the global scope and passing it as extern among class header files.

Something like this (main.cpp):

boost::program_options::variables_map vm;

int main(int argc, char* argv[]) {

    using namespace boost::program_options;
    try {
        options_description desc("Allowed options");
        desc.add_options()
        ("help,h", "produce help message")
        ("control-port,c", value<uint16_t>()->implicit_value(6016),
          "The remote TCP port used for listen to probe control connections")
        ("data-port", value<uint16_t>()->implicit_value(6026),
          "The remote TCP port used for listen to probe data connections")
        ("db-host", value<std::string>(),
          "The host name or address of MySQL database")
        ("db-port", value<uint16_t>(), "The port of MySQL database"
        ("db-user", value<std::string>(),
          "The username used to connect to MySQL database")
        ("db-pass", value<std::string>(),
          "The password used to connect to MySQL database")
        ("db-schema", value<std::string>(), "The database scheme used");

...

(DbConnector.hpp)

extern boost::program_options::variables_map vm;

(DbConnector.cpp)

 ...
DbConnector::DbConnector(const std::string& ownerName_) :
        ownerName(ownerName_) {
    dbHost = vm["db-host"].as<std::string>();
    dbPort = vm["db-port"].as<uint16_t>();
    dbUser = vm["db-user"].as<std::string>();
    dbPass = vm["db-pass"].as<std::string>();
    dbSchema = vm["db-schema"].as<std::string>();
  ...

And so on, for other classes..

I was wondering if there is a better way to achieve this, maybe avoiding the use of extern keyword.

Filippo Lauria
  • 1,965
  • 14
  • 20
  • 1
    I would recommend to represent the options in a class of their own (using plain old getter/setter functions), that implements the `boost::program_options` part, is called from main and later be passed around to other classes. – πάντα ῥεῖ Sep 04 '15 at 10:18
  • @πάνταῥεῖ I'd say the "pass it around" part of that advice is spot on: _avoid (glorified) global variables_. The rest highly depends on the context. (Don't overengineer prematurely). But yeah, the tight coupling is conspicuous in the OP's code. – sehe Sep 04 '15 at 11:15

0 Answers0