changing const values at develop-time without recompiling everything
Right now I have a considerable amount of would-be magic numbers stored in constants. These get tweaked a lot in between each build. eg const int numAPPLES = 25
right now these are each defined at the top of each associated class header. But sometimes they need to be shared and I and up having to either:
- Copy the definition; and risk conflicting values
- include extra header (which is what I've done)
I previously had them all in an options.h
which is great because I can see them all together but changing a number would obviously trigger a complete rebuil开发者_Python百科d.
If it matters I am using VS 2010.
What is the best way to allow changing these numbers? I am wondering how I could add a .txt file to my VS project and then extract the variables from there.
the data types are (for now) only char
, and int
I also don't want to have a whole library dependency just to access them. But a simple recommended class; or way to build own would be great.
thanks!
edit: does this look good to you guys?: http://www.codeproject.com/KB/cpp/IniReader.aspx
If you need the constants at compile time, you really have to recompile when they change.
If you only need the values at runtime, you can declare them as
extern const int numAPPLES;
and put the actual values in a separate .cpp file. When you change a value, you just have to recompile that one file.
Have you considered using a .ini file which is read at runtime to store all these constants?
You can then read such files using GetPrivateProfileInt
/GetPrivateProfileString
. As fas as my experience goes it is a pretty common way to deal with your situation under Windows.
Here's an example given a simple Try.ini file:
..
[Section1]
Const1 = 1
..
And the code snipper:
CString FileName = _T("Try.ini");
int Value = GetPrivateProfileInt( "Section1", "Const1", DEFAULT_ERROR, FileName );
if( Value == DEFAULT_ERROR)
return ERROR;
Cheers
Answer for edit: No, it does not look good. What are all those magic 255's scattered all over the code? It's C++ code, so what are char* strings doing there?
I guess it could be useful if it compiles as is and you're able to integrate it into your code right away. Then when you are comfortable with it, you can keep the interface and rewrite the methods for clarity and safety.
But I suggest you take a look at some libraries, and the first one that comes off the top of my head is Boost.Program_options.
精彩评论