selectany
Microsoft 特定的
告訴編譯器宣告的全域資料項目 (變數或物件) 是挑選任一個 (Pick-any) COMDAT (封裝函式)。
語法
__declspec( selectany )
宣告子
備註
在連結時,如果看見多個定義的 COMDAT,則連結器會挑選一個定義並捨棄其餘定義。 如果選取連結器選項 /OPT:REF
(優化),就會發生 COMDAT 消除動作,以移除連結器輸出中所有未參考的資料項目。
宣告中的建構函式以及由全域函式或靜態方法進行的指派不會建立參考,也不會阻止 /OPT:REF 刪除作業。 來自這類程式碼的副作用不應取決於不存在其他資料參考時。
若為動態初始化,全域物件 selectany
也會捨棄未參考物件的初始化程式碼。
全域資料項目通常只能在 EXE 或 DLL 專案中初始化一次。 selectany
當相同標頭出現在多個原始程式檔中時,可用於初始化標頭所定義的全域資料。 selectany
適用于 C 和 C++ 編譯器。
注意
selectany
只能套用至外部可見之全域資料項目的實際初始化。
範例: 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 折迭
此程式碼示範如何使用 selectany
屬性來確保當您也使用 /OPT:ICF
連結器選項時,資料 COMDAT 折迭。 請注意,資料必須標示為 , selectany
並放置在 const
(readonly) 區段中。 您必須明確指定唯讀區段。
// 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;
}
END Microsoft 特定的
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應