I have a program that I run repeatedly with various parameter sets. Different parameters are used in different parts of the program (including different source files). The same parameter may also be used in different places. However, all parameters are constant during run-time after they have been set.
I discovered very quickly that declaring the parameters locally does not make sense (it involves having to remember where every parameter is defined, etc.), so I resorted to using a params.h
where I declared and defined all the parameters: const int Param1 = 42;
, etc.
The downside of this is that I have to recompile every time I change a parameter. So I'm thinking of using the method below. It relies on usingvolatile
and const_cast
, which is normally considered "dirty", but it ensures once the parameters have been set in main
, they are not accidentally changed anywhere else in the program.
I'm wondering whether people think this is OK, because eventually I want to open-source my code.
In params.h
:
namespace Params
{
extern volatile const int Param1;
// etc.
}
In main.cpp
:
#include "params.h"
volatile const int Params::Param1 = 0;
int main(int argc, char* argv[])
{
int* const pParam1 = const_cast<int*>(Params::Param1);
*pParam1 = // Get value from argv[] or some config.ini file.
// etc.
}