Search code examples
c++c++11constantsexternboost-program-options

Define global const variables known at run-time with helper functions (c++)


I want to define a series of global variables from within a parametrise() helper function like this:

// helper.h
namespace settings {
  extern const unsigned short something;
}
namespace helper {
  void parametrise(int, char**); // parametrise from command line using boost::program_options
}

// main.cpp
int main( int argc, char** argv) {
  helper::parametrise(argc, argv);
  return 0;
}

// helper.cpp
void helper::parametrise(int, char**) {
  // parse input here
  const unsigned short settings::something = .. // this is what I want to do
}

This code does not compile of course, but there has to be a way around it.. or not?


Solution

  • You can make it writable only within that translation unit, and have it externally const, like so:

    // helper.h
    namespace settings {
      extern const unsigned short& something;
    }
    
    void parametrise(int, char**);
    
    // helper.cpp
    namespace { namespace settings_internal {
      unsigned short something;
    }}
    
    namespace settings {
      const unsigned short& something = settings_internal::something;
    }
    
    void parametrise(int, char**) { settings_internal::something = 123; }