c++ - 不能使用隐式链接的 .dll 中的类

标签 c++ dll linker dllexport

我在 ShapeTester.cpp(另一个 .dll 项目)中使用 Shape.dll 中的类 Shape 时遇到问题。

//Shape.h

#ifdef SHAPE_EXPORTS
#define SHAPE_API __declspec(dllexport)

class SHAPE_API Shape
{
public:
Shape();
Shape(int sides, int sideLength, int apothem);
~Shape();

int Perimeter();
double Area();
private:
int sides;
int sideLength;
int apothem;
};
#endif

------------------------------------------------------------
//Shape.cpp

#include "stdafx.h"
#include "Shape.h"

Shape::Shape() : sides(0), sideLength(0), apothem(0)
{
}

Shape::Shape(int sides, int sideLength, int apothem) : sides(sides), sideLength(sideLength), apothem(apothem)
{
}

Shape::~Shape()
{
}

double Shape::Area()
{
    //implementation
}

int Shape::Perimeter()
{
    //implementation
}

-----------------------------------------------------------
//ShapeTester.cpp (this is in another DLL project)
#include "stdafx.h"
#include "ShapesTester.h"
#include "Shape.h"

bool ShapesTester::Test()
{
    Shape myShape = Shape(3, 9, 5); // error here; cant resolve symbol Shape

    return myShape.Area() == 67.5;
}

我在预处理器指令中包含了 SHAPE_EXPORT,我可以获得 .dll、.lib

属性 > 配置属性 > 链接器 > 输入 > 将附加依赖项设置为 Shape.lib

Properties > configuration Properties > Linker > General> Additional Library Directories(指向 Shape.Lib 的位置)

Properties > configuration Properties > C/C++ > Additional Include Directories(指向 Shape.h 的位置)

最佳答案

您的Shape 类应该在#ifdef block 之外,而不是在其中。除非定义了 SHAPE_EXPORT 符号,否则代码不会声明 Shape 类。

你想做的是

#ifdef SHAPE_EXPORTS
#define SHAPE_API __declspec(dllexport)
#else
#define SHAPE_API __declspec(dllimport)
#endif

class SHAPE_API Shape
// etc

关于c++ - 不能使用隐式链接的 .dll 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50438275/

相关文章:

c - 隐式动态链接与显式动态链接 - 哪个更有效?

c - 将变量放在特定地址会生成大型二进制文件

c++ - 如何调用 char 构造函数而不是 char[] 构造函数

c++ - 具有特定参数列表的函数指针

c++ - 即使我用 -L 指定了它的位置,链接器也找不到库

windows - 使用 Go 1.7 构建 dll

vb.net - 在特定时间播放声音-Winmm.dll-VB.Net

c++ - 测试 Doom 3 Stack 实现时堆栈损坏

c++ - 如何从 DLL 导出模板?

c++ - 64位系统上Visual Studio 2012 32位编译