【发布时间】:2018-05-08 06:54:44
【问题描述】:
在链接 DLL 的工作方式方面,我的知识有点模糊,但我观察到可执行文件中静态成员变量的更改不会更改 DLL 中的相同静态成员变量。这是我的场景:
main.cpp 静态链接到 mylib.lib。在 mylib.lib 中,我有以下类:
// foo.h
class Foo
{
public:
static int m_global;
Foo();
~Foo();
};
和
// foo.cpp
#include "foo.h"
int Foo::m_global = 5;
我还有一个链接到 mylib.lib 的 DLL,其中包含以下内容:
//testdll.h
#define MATHLIBRARY_API __declspec(dllimport)
void MATHLIBRARY_API printFoo();
和
// testdll.cpp
#include "testdll.h"
#include <iostream>
void printFoo() {
std::cout << Foo::m_global << std::endl;
}
最后,在我的可执行文件的 main.cpp 中
// main.cpp
#include <iostream>
#include "testdll.h"
#include "foo.h"
int main() {
std::cout << Foo::m_global << std::endl;
Foo::m_global = 7;
std::cout << Foo::m_global << std::endl;
printMutiply();
return 0;
}
我的预期输出是 5、7、7。但是,我看到 5、7、5,这告诉我 DLL 没有看到静态成员变量更改。为什么会这样?以及如何让 DLL 看到可执行文件中静态成员变量的变化??
【问题讨论】:
-
如果您编译 DLL,
class foo必须与__declspec(dllexport)一起归属。如果您编译可执行文件,则(相同的)class foo必须归属于__declspec(dllimport)。这通常是使用一些宏技巧来完成的(例如,由我们完成)。我发现了一个相关的 SO Q/A:SO: Macro for dllexport/dllimport switch,这可能会有所帮助。