如何防止VC ++ 9链接器链接不必要的全局变量? [英] How to prevent VC++ 9 linker from linking unnecessary global variables?
问题描述
我正在玩函数级链接在VC ++中.我已启用/OPT:REF和/OPT:ICF,链接器很高兴消除所有未使用的功能.变量不是这样.
I'm playing with function-level linking in VC++. I've enabled /OPT:REF and /OPT:ICF and the linker is happy to eliminate all unused functions. Not so with variables.
以下代码仅用于演示问题,我完全理解,实际上以这种方式构造代码是次优的.
The following code is to demonstrate the problem only, I fully understand that actually having code structured that way is suboptimal.
//A.cpp
SomeType variable1;
//B.cpp
extern SomeType variable1;
SomeType variable2;
class ClassInB {
//actually uses variable1
};
//C.cpp
extern SomeType variable2;
class ClassInC {
//actually uses variable2;
};
所有这些文件都被编译成静态库.消费者项目仅使用 ClassInC
并链接到静态库.现在出现了VC ++ 9链接器.
All those files are compiled into a static lib. The consumer project only uses ClassInC
and links to the static library. Now comes the VC++ 9 linker.
首先,链接程序会看到 C.obj
引用了 variable2
,并包含了 B.obj
. B.obj
引用 variable1
,因此它包含 A.obj
.然后未引用的东西消除阶段开始.它删除 A.obj
和 B.obj
中的所有函数,但不删除变量. variable
和 variable2
都与它们的静态初始化程序和反初始化程序一起保存.这会放大图像的大小,并会导致运行初始化程序和取消初始化的延迟.
First the linker sees that C.obj
references variable2
and includes B.obj
. B.obj
references variable1
, so it includes A.obj
. Then the unreferenced stuff elimination phase starts. It removes all functions in A.obj
and B.obj
, but not the variables. Both variable
and variable2
are preserved together with their static initializers and deinitializers. That inflates the image size and introduces a delay for running the initializers and deinitializes.
上面的代码过于简单,在实际代码中,我真的不能轻易地将 variable2
移到 C.cpp
中.我可以将其放入一个单独的.cpp文件中,但这看起来真是愚蠢.有没有更好的选择来解决Visual C ++ 9的问题?
The code above is oversimplified, in actual code I really can't move variable2
into C.cpp
easily. I could put it into a separate .cpp file, but that looks really dumb. Is there any better option to resolve the problem with Visual C++ 9?
推荐答案
MSDN (请参见 Arguments
部分, REF | NOREF
参数,第4段)指定您必须显式将数据标记为COMDAT;使用__declspec(selectany).
链接器可以在使用/OPT:REF
时删除未使用的数据.
The MSDN (see the Arguments
section, REF | NOREF
arguments, 4th paragraph) specifies that You have to explicitly mark data as a COMDAT; use __declspec(selectany).
for the linker to remove said unused data when using /OPT:REF
.
您是否尝试过并有机会使用 __declspec(selectany)?
Have you tried and had any chance with __declspec(selectany) ?
这篇关于如何防止VC ++ 9链接器链接不必要的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!