C, C++ 문법

__declspec( selectany ) declarator

디버그정 2008. 9. 2. 12:10

아래글을 요약하자면, 여러번 정의가 된 경우, 아무거나 하나 고른다...
헤더파일에 선언뿐 아니라 정의까지 넣는 경우 중복 문제로 컴파일이
되지 않는데 그런 경우 쓰면 좋다... 실제로 component의 작성시 헤더화일에
위 지시자를 쓰면서 guid 정의를 같이 하는 경우가 있다.

extern "C" const GUID __declspec(selectany) LIBID_MYCTRLLib  
 =    {0xcd886b0a,0x2d92,0x40fe,{0xb0,0x1f,0x72,0x83,0x6c,0x14,0x3e,0xe2}};

extern "C" const GUID __declspec(selectany) CLSID_MyTest
 =  {0x66483f99,0x21ff,0x45a0,{0xa5,0xcc,0x75,0xa2,0x7b,0x9f,0x50,0x68}};

extern "C" const GUID __declspec(selectany) IID_IMyTest
 =   {0xcfe30c72,0x2400,0x4cb7,{0xae,0xa2,0xae,0x09,0xc5,0x0c,0x58,0x45}};

 //////////// msdn ////////////

__declspec( selectany )
declarator

This attribute tells the compiler that the declared global data item is a pick-any COMDAT. 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.

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

Note   This attribute can only be applied to the actual initialization of global data items that are externally visible.

END Microsoft Specific

Example

This code shows how to use the selectany attribute:

//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;