2

我不能完全弄清楚哪里有错误。我正在创建一个 DLL,然后在 C++ 控制台程序(Windows 7、VS2008)中使用它。但是我LNK2019 unresolved external symbol在尝试使用 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包含在Linker->General->Additional Library Directories中:

#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
}

我不知道这里出了什么问题;它必须是非常简单和基本的东西。

4

2 回答 2

12

您正在导出一个类成员函数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应该定义。两个项目都必须,但只有 DLL 项目应该包含#include "Foo.h""Foo.cpp"

然后,当您构建 DLL 时,类 Foo 及其所有成员都被标记为“从此 DLL 导出”。当您构建任何其他项目时,类 Foo 及其所有成员都被标记为“从 DLL 导入”

于 2011-04-14T21:33:19.543 回答
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
}
于 2012-10-05T14:59:27.580 回答