c ++导出和使用dll函数

sci*_*gor 2 c++ dll dllimport dllexport

我无法弄清楚哪里有错误.我正在创建一个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
Run Code Online (Sandbox Code Playgroud)

这是我用于的一个头文件:

#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
Run Code Online (Sandbox Code Playgroud)

然后在控制台程序中有dllimport,它包含在Linker-> General-> Additional Library Directories中的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
}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚这里出了什么问题; 它必须是非常简单和基本的东西.

Eri*_*rik 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 {
...
}:
Run Code Online (Sandbox Code Playgroud)

控制台项目将会看到:

class  __declspec(dllimport) MyFuncLibInterface {
...
}:
Run Code Online (Sandbox Code Playgroud)

这允许您的控制台项目使用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
Run Code Online (Sandbox Code Playgroud)

Foo::bar() BUILDING_THE_DLL必须定义实际实现的项目中.在它试图项目使用 Foo,BUILDING_THE_DLL应该不会被定义.两个项目都必须#include "Foo.h",但只有DLL项目应该包含"Foo.cpp"

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