Candy wrote:If you want to explicitly tell it that you won't put it in other files (so it can certainly perform this optimization) put them in an anonymous namespace.
A namespace isn't strictly needed for constants as they're already by default local in C++. It's even possible to use different values for the same constants in different source-files:
Code: Select all
(code_one.cpp) -> const int a = 0xABC; // local variable
(code_two.cpp) -> const int a = 0xDEF; // local variable
If you want a constant to be visible outside of your module it must be declared as extern. This overrides the default behaviour and allows you to refere to the variable from other modules:
Code: Select all
(code_one.cpp) -> extern const int a = 0xABC; // global variable (definition)
(code_two.cpp) -> extern const int a; // extern variable (declaration)
At the moment I unfortunately can't find any useful references about this topic on the internet. My Stroustrup however does include some bits of information in chapters §9.2 (linkage of constants) and §5.4 (constants and optimization). If I remember correctly you once mentioned having a copy of the book ?
Neo wrote:But it would still occupy space in the object files right? So if we only replace object files and not binaries this would cause a waste of memory?
It really depends on the constants you want to use. If their value is known to the compiler when it parses through your source there's no need to create any object. Every occurance of your constant in the source will be replaced by an immediate value and there won't be any variable in the object-files or the binary. If the value of the constant isn't know to the compiler a variable has to be created.
Code: Select all
const int c0 = 0xDEADBABE; // Known at compilation time
const int c1 = CreateRandom(time); // Unknown -> object needed
extern const int c2; // Unknown -> one (!) object needed
const int* p = &c0; // Object for c0 needed
Note that arrays of constants usually have to be created in memory as it's impossible for the compiler to know in advance how the data will get accessed. If you want to use such large structures you should probably use global variables to save memory. Local constants should be used for integers (f.ex. magic values) to get the best performance and save memory.
cheers,
gaf