静态const与#define在C ++中-可执行文件大小的差异 [英] static const vs. #define in c++ - differences in executable size
问题描述
我的基本情况:我有一个包含文件,其内容类似于 #define foo(Flag1 | Flags2 | Flag3)
,因此它是位标志的预定义组合。为了确保类型安全,我想将这些#defines替换为静态const,即 static const int foo =(Flag1 | Flag2 | Flag3)
(或类似名称)。该包含文件包含在程序的数十个位置中。
My basic situation: I have an include file that has something like #define foo (Flag1 | Flags2 | Flag3)
, so it's a predefined combination of bit flags. For the sake of type-safety, I wanted to replace these #defines by static consts, i.e. static const int foo = (Flag1 | Flag2 | Flag3)
(or similar). This include file is included in dozens of places in the program.
现在,当我在发布版本中启用了所有相关的优化选项时(使用VS2010的C ++编译器) ),替换#defines似乎会使可执行文件增加几KiB,具体取决于我替换了多少个常量。
Now when I'm doing a release build with all relevant optimisation options enabled (using the C++ compiler of VS2010), replacing the #defines seems to increase the executable by a few KiB, depending on how many constants I replaced.
为什么会这样?据我所知,如果可能的话,应该将整数常量内联到生成的ASM代码中,而且我看不到如何使用 static const
vs #define
在这里会有所作为。显然,反汇编显示该变量不是内联的:
Why does this happen? To my knowledge, integer constants are supposed to be "inlined" into the ASM code that is produced if possible, and I don't see how using a static const
vs #define
would make a difference here. Clearly, the variable isn't inlined as the disassembly shows:
#define:
01325041 or eax,0FFD87FE0h
static int:
011E5451 or eax,dword ptr [CMainFrame::s_TemplateModulePaths+38h (151F008h)]
最后一个问题是:如何避免 #define
但仍然依赖于直接将变量插入到生成的程序集中?
So the final question is: How can I avoid #define
but still rely on the variable being inserted directly into the generated assembly?
推荐答案
如注释所示,类型安全运算符|我的枚举的重载似乎阻止VC ++内联ORed值。我想我会继续使用 #define
版本,因为我讨厌在没有好处的情况下增加可执行文件的大小(不,这不是过早的优化)-毕竟,它没有不会增加可读性,并且由于标记的组合已经是我的flagset枚举类型,我想我也不会失去任何类型安全性。
As seen in the comments, the typesafe operator| overloading for my enums seems to prevent VC++ from inlining the ORed value. I guess I'll keep using the #define
version as I hate increasing the executable size if there's no benefits (no, this is not premature optimization) - after all, it doesn't increase readability, and since the combination of flags is already of my flagset enum type, I also don't lose any type-safety, I guess.
这篇关于静态const与#define在C ++中-可执行文件大小的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!