导出DLL中的静态数据 [英] Exporting static data in a DLL
问题描述
我有一个DLL,其中包含具有静态成员的类。为了使用这个类的方法,我使用 __ declspec(dllexport)
。但是当我将它链接到另一个项目并尝试编译它,我得到静态数据的未解决的外部符号错误。
I have a DLL which contains a class with static members. I use __declspec(dllexport)
in order to make use of this class's methods. But when I link it to another project and try to compile it, I get "unresolved external symbol" errors for the static data.
在DLL中,Test.h
e.g. In DLL, Test.h
class __declspec(dllexport) Test{
protected:
static int d;
public:
static void m(){int x = a;}
}
b $ b
在DLL中,Test.cpp
In DLL, Test.cpp
#include "Test.h"
int Test::d;
在使用Test的应用程序中,我调用m()。
In the application which uses Test, I call m().
我也尝试使用__declspec(dllexport)分别为每个方法,但我仍然得到相同的链接错误为静态成员。
I also tried using __declspec(dllexport) for each method separately but I still get the same link errors for the static members.
如果我检查
例如,应用程序在链接时提供以下错误:
For instance, the app gives the following error at link time:
1>Main.obj : error LNK2001: unresolved external symbol "protected: static int CalcEngine::i_MatrixRow" (?i_MatrixRow@CalcEngine@@1HA)
但是.lib的dumpbin包含:
But the dumpbin of the .lib contains:
Version : 0
Machine : 14C (x86)
TimeDateStamp: 4BA3611A Fri Mar 19 17:03:46 2010
SizeOfData : 0000002C
DLL name : CalcEngine.dll
Symbol name : ?i_MatrixRow@CalcEngine@@1HA (protected: static int CalcEngine::i_MatrixRow)
Type : data
Name type : name
Hint : 31
Name : ?i_MatrixRow@CalcEngine@@1HA
不能弄清楚如何解决这个问题。我做错了什么?如何解决这些错误?
I can't figure out how to solve this. What am I doing wrong? How can I get over these errors?
该代码最初是为Linux开发的,而.so / binary组合的工作没有问题。
P.S. The code was originally developed for Linux and the .so/binary combination works without a problem
编辑:在给定的情况下,静态变量不直接由应用程序引用但方法是内联的,因为它在标题中。我可以通过将方法移动到.cpp文件来解决链接错误。
In the given case, the static variables are not directly referred by the application but the method is inlined since it's in the header. I was able to resolve the link errors by moving the methods to the .cpp file.
推荐答案
在这个线程在cprogramming.com建议静态变量是本地的dll,而不是
In this thread at cprogramming.com it is suggested that a static variable is local to the dll and not exported.
静态成员不能通过调用应用程序中的代码直接访问,只有通过成员函数的类在dll。但是,有几个 inline 函数访问静态成员。这些函数将被内联扩展到调用应用程序代码中,使调用应用程序直接访问静态成员。这将违反上面提到的静态变量是本地的dll,不能从调用应用程序引用的发现。
The static member is not accessed directly by code in the calling application, only through member functions of the class in the dll. However there are several inline functions accessing the static member. Those functions will be inline expanded into the calling applications code makeing the calling application access the static member directly. That will violate the finding referenced above that static variables are local to the dll and cannot be referenced from the calling application.
这篇关于导出DLL中的静态数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!