I have a C++ code that's a physics simulation tool.
I would like to store some physical constants, conversion factor between different sets of units, and also some more application specific constants (such as definit开发者_运维百科ion like enum Planes {X=0, Y=1}
) and I would like to be able to access them from everywhere in my code.
What would be the best way to do that ?
I think one way would be to create a namespace namespace constants
(which can then be a nested namespace in my main namespace) with nested namespaces (like 'constants', 'units', etc.).
Would it be the way you would do that ?
If I use that method, do I have to make it a header file and include it everywhere ?
If I understand correctly the variables in the namespace at global scope have static
linkage, but no external
linkage. Then if I want to use them without including a file, I also have to declare them extern
?
As you can see I am a bit confused about that...
Namespace constants are the way to go in most cases.
If I use that method, do I have to make it a header file and include it everywhere ?
Yes, or not everywhere but only where it's really USED.
If I understand correctly the variables in the namespace at global scope have static linkage, but no external linkage. Then if I want to use them without including a file, I also have to declare them extern ?
Yes, you have to do it that way :
// header
namespace modulename
{
// maybe add another namespace to specify that you have constants, but taste-dependant
namespace domain // like maths or physics
{
extern const Number THIS_NUMBER; // have to be defined in the cpp
extern const int THAT_NUMBER = 256; // if it's int-based type, you can define it -here - BUT DON'T IF IT CAN BE CHANGED : all files including this one would have to be recompiled at each value change!!
}
}
// .cpp, where you have the definitions
namespace modulename
{
namespace domain // like maths or physics
{
const Number THIS_NUMBER = Number( 256.42f ); // definition - static is implicit
}
}
If the compiler doesn't say anything about it being unrecognized then you are safe. All that matters is that the compiler knows where to find the variable. Once you include the header file, it is technically a copy and paste of the code in that file. Given this, you need to do some precompiler directives.
#ifndef _MYGLOBALS
#define _MYGLOBALS
int global_integer;
long global_long;
#endif
This ensures that they will only be included once, and you will not have many references of the variables in your code.
I'd make a constants namespace and put in all globally-relevant constants there. Any constants only relevant to a single class, declare as static consts within the class itself.
精彩评论