定義和宣告 (C++)

Microsoft 特定的

DLL 介面是指系統中某些程式已知要匯出的所有專案(函式和資料):也就是說,宣告為 dllimportdllexport 的所有專案。 DLL 介面中包含的所有宣告都必須指定 dllimportdllexport 屬性。 不過,定義只能指定 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 特定的

另請參閱

dllexport、dllimport