gpt4 book ai didi

c++ - DLL 中的静态数据

转载 作者:可可西里 更新时间:2023-11-01 14:42:01 24 4
gpt4 key购买 nike

我的问题与 this one 非常相似: DLL 中的类有一个静态成员。在这种情况下,静态成员的类型为 QString (QT 类型)并为类提供名称。我在类级别提供正常导出:__declspec(dllexport)

当我将 DLL 与我的类链接到另一个项目并尝试对其进行编译时,我收到静态数据的“未解析的外部符号”错误。我验证了两件事:

  1. Dumpbin 明确报告要由已编译的 DLL 导出的静态数据成员。
  2. 实际上,静态数据成员似乎没有在报告错误的应用程序中使用。

DLL 中的 HEADER 文件 (.h) 是:

class __declspec(dllexport) MyClass {
public:
virtual ~MyClass();
static const QString JUST_A_NAME;
};

DLL 中的实现文件 (.cpp) 是:

#include "MyClass.h"

MyClass::~MyClass() { }
const QString MyClass::JUST_A_NAME("call_me_al");

对比already mentioned post,我避免了内联的方法,例如实现显然不在标题中。类型,QString (参见第 83 行 ff.),本身包含几个内联。这可能会导致错误吗?

编辑: 我在应用程序的 header 中添加了一个导入语句。它位于任何包含之前。APPLICATION 中的 HEADER 文件 (.h) 是:

class __declspec(dllimport) MyClass {
public:
virtual ~MyClass();
static const QString JUST_A_NAME;
};

错误依旧:

error LNK2001: non resolved external symbol ""public: static class QString const MyClass::JUST_A_NAME" (?JUST_A_NAME@MyClass@@2VQString@@B)". <name of .obj file from application>

最佳答案

在您的应用程序头文件中,您需要做两件事。

  1. 导出时声明定义__declspec(dllexport)
  2. 导入时声明定义__declspec(dllimport)

你显然不能同时做这两件事。

你所要做的就是像这样定义一个宏:

#ifdef __COMPILING_MYLIB
#define MYLIBAPI __declspec(dllimport)
#else
#define MYLIBAPI __declspec(dllexport)
#endif

然后像这样声明你的导出:

// mylib.h
class MYLIBAPI MyClass {
public:
virtual ~MyClass();
static const QString JUST_A_NAME;
};

然后,在编译 MYLIB 时,将 -D__COMPLING_MYLIB 传递给编译器,这会触发上面的 #if

这样,当编译库本身时,头文件声明为导出,但是当编译将使用库的东西时,它们被声明为导入。

关于c++ - DLL 中的静态数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14627597/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com