问题描述
我有一堆常量,我想在我的代码的不同部分访问,但我想要作为一个整体容易访问:
c> c> c> c> code>文件,但是您将失去优化的潜力,因为编译器不会知道在编译每个.cpp时它们具有什么值。
顺便提一句,不要担心大小增加:对于整数类型,常量可能直接内联在生成的机器代码中。
最后, static 不是必需的,因为默认情况下 const 是C ++中的 static 。
I have a whole bunch of constants that I want access to in different parts of my code, but that I want to have easy access to as a whole:
static const bool doX = true; static const bool doY = false; static const int maxNumX = 5;etc.
So I created a file called "constants.h" and stuck them all in there and #included it in any file that needs to know a constant.
Problem is, this is terrible for compile times, since every time I change a constant, all files that constants.h reference have to be rebuilt. (Also, as I understand it, since they're static, I'm generating a copy of doX/doY/maxNumX in code every time I include constants.h in a new .cpp, leading to kilobytes of wasted space in the compiled EXE -- is there any way to see this?).
So, I want a solution. One that isn't "declare constants only in the files that use them", if possible.
Any suggestions?
解决方案The only alternative is to make your constants extern and define them in another .cpp file, but you'll lose potential for optimization, because the compiler won't know what value they have when compiling each .cpp`.
By the way, don't worry about the size increase: for integral types your constants are likely to be inlined directly in the generated machine code.
Finally, that static is not necessary, since by default const global variables are static in C++.
这篇关于C ++常量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!