我无法弄清楚哪里有错误。我正在创建一个DLL,然后在C++控制台程序(Windows 7,VS2008)中使用它。但是尝试使用DLL函数时出现LNK2019 unresolved external symbol

首先导出:

#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,该DLLimport包含在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
}

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

最佳答案

您正在导出类成员函数void MyFuncLibInterface::myFunc(std::string param);,但尝试导入免费函数void myFunc(std::string param);
确保您在DLL项目中使用#define MyFuncLib_EXPORTS。确保在控制台应用程序中未定义#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导入”

关于c++ - C++导出和使用dll函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5669937/

10-11 20:31
查看更多