C++ c++;导出和使用dll函数
我不太清楚哪里出了错。我正在创建一个DLL,然后在C++控制台程序(Windows 7,VS2008)中使用它。但在尝试使用DLL函数时,我得到了C++ c++;导出和使用dll函数,c++,dll,dllimport,dllexport,C++,Dll,Dllimport,Dllexport,我不太清楚哪里出了错。我正在创建一个DLL,然后在C++控制台程序(Windows 7,VS2008)中使用它。但在尝试使用DLL函数时,我得到了LNK2019未解析的外部符号 首先是出口: #ifndef __MyFuncWin32Header_h #define __MyFuncWin32Header_h #ifdef MyFuncLib_EXPORTS # define MyFuncLib_EXPORT __declspec(dllexport) # else # define My
LNK2019未解析的外部符号
首先是出口:
#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
然后是console程序中的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
}
#包括
#包括
#包括
__declspec(dllimport)void myFunc(std::string param);
int main(int argc,const char*argv[]
{
std::string inputPar=“bla”;
myFunc(inputPar);//此行生成链接器错误
}
我不知道这里出了什么问题;它必须是非常简单和基本的东西 您正在导出一个类成员函数void MyFuncLibInterface::myFunc(std::string param)代码>但试图导入一个自由函数void myFunc(std::string param)代码>
确保在DLL项目中定义MyFuncLib_导出。确保在控制台应用程序中包含“MyFuncLibInterface.h”
,而不定义MyFuncLib\u导出
DLL项目将看到:
class __declspec(dllexport) MyFuncLibInterface {
...
}:
class __declspec(dllimport) MyFuncLibInterface {
...
}:
控制台项目将看到:
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
在实际实现构建的项目中,必须定义DLL。在尝试使用Foo
的项目中,不应定义构建DLL
。两个项目都必须#包含“Foo.h”
,但只有DLL项目应该包含“Foo.cpp”
然后构建DLL时,类Foo及其所有成员都标记为“从此DLL导出”。当您构建任何其他项目时,类Foo及其所有成员都标记为“从DLL导入”您需要导入类而不是函数。之后,您可以调用该类成员
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
}
回答得好;基本上就是我注意到的。另外,函数没有声明为静态的,所以需要一个类的实例来调用函数。我是否应该将Interface.h从#imports中剥离出来,并将其定义并包含在console项目中?可以说得更具体一点吗。@inf.ig.sh:如果要使用console项目中的类,必须在console项目中包含.h。console项目需要查看声明为dllimport的类,以便在DLL中查找实际实现。很好的答案。我只有一个后续问题。你能解释更多关于#定义MyFuncLib_导出的内容吗?你的意思是说所有需要的是把这行代码放到dll中,而不是别的。