Share via


>selectany

Microsoft 專有的

讓編譯器知道,宣告的全域資料的項目 (變數或物件) 會挑選任何的衝突 (包裝函式)。

__declspec( selectany ) declarator

備註

連結時,如果被發現衝突的多重定義,連結器會挑選其中一個,並捨棄其餘部分。 如果連結器選項 /OPT:REF (最佳化) 已選取,則會繼續 COMDAT 消去法,連結器輸出中移除所有未參考的資料項目。

建構函式和全域函式或靜態方法宣告中的工作分派不會建立參考,並不會防止 /OPT:REF 消去法。 不應該將這類程式碼的副作用相依於,沒有其他參考資料存在時。

對於以動態方式初始化的全域物件, selectany將會捨棄未參考的物件初始化程式碼,以及。

EXE 或 DLL 的專案中通常初始化一次的全域資料的項目。 selectany可在初始化時相同的頁首會出現一個以上的原始程式檔中,標頭,所定義的全域資料。 selectany在 c 和 C++ 編譯器中使用。

注意事項注意事項

selectany只可以套用到實際的初始設定的全域資料是外部可見的項目。

範例

這段程式碼示範如何使用selectany屬性:

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

這段程式碼示範如何使用selectany屬性,以確保資料 COMDAT 摺,當您使用 /OPT:ICF 連結器選項。 請注意必須以標記資料selectany ,並放在 const (唯讀)] 區段。 您必須明確指定的 [唯讀] 區段。

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

結束 Microsoft 特定

請參閱

參考

__declspec

C + + 關鍵字