2011-04-14 117 views
2

我無法弄清楚哪裏有錯誤。我正在創建一個DLL,然後在C++控制檯程序(Windows 7,VS2008)中使用它。但是當我嘗試使用DLL函數時,我得到了LNK2019 unresolved external symbolC++導出和使用dll函數

首先是出口:

#ifndef __MyFuncWin32Header_h 
#define __MyFuncWin32Header_h 

#ifdef MyFuncLib_EXPORTS 
# define MyFuncLib_EXPORT __declspec(dllexport) 
# else 
# define MyFuncLib_EXPORT __declspec(dllimport) 
# endif 

#endif 

這是一個頭文件,然後我用:

#ifndef __cfd_MyFuncLibInterface_h__ 
#define __cfd_MyFuncLibInterface_h__ 

#include "MyFuncWin32Header.h" 

#include ... //some other imports here 

class MyFuncLib_EXPORT MyFuncLibInterface { 

public: 

MyFuncLibInterface(); 
~MyFuncLibInterface(); 

void myFunc(std::string param); 

}; 

#endif 

再有就是dllimport的控制檯程序,其中有包含在鏈接器的DLL - >一般 - >其他圖書館目錄:

#include <stdio.h> 
#include <stdlib.h> 
#include <iostream> 


__declspec(dllimport) void myFunc(std::string param); 


int main(int argc, const char* argv[]) 
{ 
    std::string inputPar = "bla"; 
    myFunc(inputPar); //this line produces the linker error 
} 

我想不通她怎麼了Ë;它必須是非常簡單和基本的東西。

回答

10

要導出類成員函數void MyFuncLibInterface::myFunc(std::string param);而是試圖導入一個免費功能void myFunc(std::string param);

確保您#define MyFuncLib_EXPORTS在DLL項目。請確保您在#include "MyFuncLibInterface.h"控制檯應用程序沒有定義MyFuncLib_EXPORTS

DLL項目將看到:

class __declspec(dllexport) MyFuncLibInterface { 
... 
}: 

和控制檯項目將看到:

class __declspec(dllimport) MyFuncLibInterface { 
... 
}: 

這使您的控制檯項目使用類從DLL。

編輯:在回答評論

#ifndef FooH 
#define FooH 

#ifdef BUILDING_THE_DLL 
#define EXPORTED __declspec(dllexport) 
#else 
#define EXPORTED __declspec(dllimport) 
#endif 

class EXPORTED Foo { 
public: 
    void bar(); 
}; 


#endif 

在實際上實現Foo::bar()BUILDING_THE_DLL必須定義項目。在試圖的項目中使用Foo,BUILDING_THE_DLL應該而不是被定義。 兩個項目必須#include "Foo.h",但只有DLL項目應該包含"Foo.cpp"

當你再建的DLL,類Foo和它的所有成員都被標記爲「從這個DLL導出」。當您構建任何其他項目時,Foo類及其所有成員都標記爲「從DLL導入」

+0

不錯的答案;基本上我注意到了。另外,函數沒有被聲明爲靜態的,所以你需要一個類的實例來調用函數。 – 2011-04-14 21:35:20

+0

我不太喜歡answear。我應該剝離#imports的Interface.h並定義並將其與控制檯項目一起使用?你能更具體些嗎? – 2011-04-15 07:24:22

+0

@ inf.ig.sh:如果要使用控制檯項目中的類,則必須在控制檯項目中包含.h。控制檯項目需要看到聲明爲* dllimport *的類,以便它可以查找DLL中的實際實現。 – Erik 2011-04-15 07:33:41

1

您需要導入類而不是函數。之後,你可以打電話給班級成員。

class __declspec(dllimport) MyFuncLibInterface { 

public: 

MyFuncLibInterface(); 
~MyFuncLibInterface(); 

void myFunc(std::string param); 

}; 

int main(int argc, const char* argv[]) 
{ 
std::string inputPar = "bla"; 
MyFuncLibInterface intf; 
intf.myFunc(inputPar); //this line produces the linker error 
}