1

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?

Marinos K
  • 1,779
  • 16
  • 39
  • Why are you using `extern`? – Ed Heal Jan 24 '16 at 18:07
  • You can not declare a global variable const if you want to modify it (via argc and argv) –  Jan 24 '16 at 18:08
  • @Ed I'm using extern 'cause otherwise I have to initialise immediately the variable and then, even-though I can change its value later, there goes the const-ness.. – Marinos K Jan 24 '16 at 18:21
  • @Dieter, that's what I'm trying to figure out. so what would be a nice alternative? I need some kind of guarantee that settings::something won't be accidentally mutated during the program's lifetime – Marinos K Jan 24 '16 at 18:21
  • So you cannot decide on the value before compilation. So why is it const when not part of an object – Ed Heal Jan 24 '16 at 18:23
  • why should it be part of an object? it's just a const variable to ensure the it's only assigned a value just ONCE. – Marinos K Jan 24 '16 at 18:48

1 Answers1

4

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; }
Yam Marcovic
  • 7,953
  • 1
  • 28
  • 38