A program I am working on has many constants that apply throughout all classes. I want to make one header file “Constants.h”, and be able to declare all the relevant constants. Then in my other classes, I can just include #include "Constants.h.
I got it to work fine using #ifndef … #define ... syntax. However, I would prefer to use the const int... form of constants. I’m not quite sure how to though.
You could simply define a series of
const intsin a header file:This works because in C++ a name at namespace scope (including the global namespace) that is explicitly declared const and not explicitly declared extern has internal linkage, so these variables would not cause duplicate symbols when you link together translation units. Alternatively you could explicitly declare the constants as static.
This is more compatible with C and more readable for people that may not be familiar with C++ linkage rules.
If all the constants are ints then another method you could use is to declare the identifiers as enums.
All of these methods use only a header and allow the declared names to be used as compile time constants. Using
extern const intand a separate implementation file prevents the names from being used as compile time constants.Note that the rule that makes certain constants implicitly internal linkage does apply to pointers, exactly like constants of other types. The tricky thing though is that marking a pointer as
constrequires syntax a little different that most people use to make variables of other types const. You need to do:to make a constant pointer, so that the rule will apply to it.
Also note that this is one reason I prefer to consistently put
constafter the type:int constinstead ofconst int. I also put the*next to the variable: i.e.int *ptr;instead ofint* ptr;(compare also this discussion).I like to do these sorts of things because they reflect the general case of how C++ really works. The alternatives (
const int,int* p) are just special cased to make some simple things more readable. The problem is that when you step out of those simple cases, the special cased alternatives become actively misleading.So although the earlier examples show the common usage of
const, I would actually recommend people write them like this:and