定義和宣告 (C++)
Microsoft 特定的
DLL 介面是指系統中某些程式已知要匯出的所有專案(函式和資料):也就是說,宣告為 dllimport
或 dllexport
的所有專案。 DLL 介面中包含的所有宣告都必須指定 dllimport
或 dllexport
屬性。 不過,定義只能指定 dllexport
屬性。 例如,下列函式定義會產生編譯器錯誤:
__declspec( dllimport ) int func() { // Error; dllimport
// prohibited on definition.
return 1;
}
此程式碼也會產生錯誤:
__declspec( dllimport ) int i = 10; // Error; this is a definition.
不過,這個語法是正確的:
__declspec( dllexport ) int i = 10; // Okay--export definition
使用 dllexport
表示定義,同時 dllimport
表示宣告。 您必須使用 extern
關鍵字搭配 dllexport
以強制進行宣告,否則其中會隱含宣告。 因此,下列範例是正確的:
#define DllImport __declspec( dllimport )
#define DllExport __declspec( dllexport )
extern DllExport int k; // These are both correct and imply a
DllImport int j; // declaration.
下列範例釐清前述範例:
static __declspec( dllimport ) int l; // Error; not declared extern.
void func() {
static __declspec( dllimport ) int s; // Error; not declared
// extern.
__declspec( dllimport ) int m; // Okay; this is a
// declaration.
__declspec( dllexport ) int n; // Error; implies external
// definition in local scope.
extern __declspec( dllimport ) int i; // Okay; this is a
// declaration.
extern __declspec( dllexport ) int k; // Okay; extern implies
// declaration.
__declspec( dllexport ) int x = 5; // Error; implies external
// definition in local scope.
}
END Microsoft 特定的
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應