aurain
技术文摘
posts - 137,  comments - 268,  trackbacks - 0

Tells the compiler that the declared global data item (variable or object) is a pick-any COMDAT (a packaged function).


__declspec( selectany ) declarator

At link time, if multiple definitions of a COMDAT are seen, the linker picks one and discards the rest. If the linker option /OPT:REF (Optimizations) is selected, then COMDAT elimination will occur to remove all the unreferenced data items in the linker output.

Constructors and assignment by global function or static methods in the declaration do not create a reference and will not prevent /OPT:REF elimination. Side effects from such code should not be depended on when no other references to the data exist.

For dynamically initialized, global objects, selectany will discard an unreferenced object's initialization code, as well.

A global data item can normally be initialized only once in an EXE or DLL project. selectany can be used in initializing global data defined by headers, when the same header appears in more than one source file. selectany is available in both the C and C++ compilers.


//Correct - x1 is initialized and externally visible 
__declspec(selectany) int x1=1;

//Incorrect - const is by default static in C++, so 
//x2 is not visible externally (This is OK in C, since
//const is not by default static in C)
const __declspec(selectany) int x2 =2;

//Correct - x3 is extern const, so externally visible
extern const __declspec(selectany) int x3=3;

//Correct - x4 is extern const, so it is externally visible
extern const int x4;
const __declspec(selectany) int x4=4;

//Incorrect - __declspec(selectany) is applied to the uninitialized
//declaration of x5
extern __declspec(selectany) int x5;

// OK: dynamic initialization of global object
class X {
public:
X(int i){i++;};
int i;
};

__declspec(selectany) X x(1);

This code shows how to use the selectany attribute to ensure data COMDAT folding when you also use the /OPT:ICF linker option. Note that data must be marked with selectany and placed in a const (readonly) section. You must explicitly specify the read-only section.

// selectany2.cpp
// in the following lines, const marks the variables as read only
__declspec(selectany) extern const int ix = 5;
__declspec(selectany) extern const int jx = 5;
int main() {
   int ij;
   ij = ix + jx;
}

 

posted on 2013-01-14 00:03 阅读(597) 评论(0)  编辑 收藏 引用 所属分类: vc

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(17)

随笔分类(138)

随笔档案(137)

网络开发

最新随笔

搜索

  •  

积分与排名

  • 积分 - 493570
  • 排名 - 36

最新随笔

最新评论

阅读排行榜

评论排行榜