整个应用程序中的变量
我有一个 C++ Windows 应用程序,它由多个 DLL 组成。 我想要有某种类型的池,我可以从中获取对象,但在某种程度上,这个池 将在所有 DLL 中可用。
所以我把它放在一个每个人都可以访问的“通用”dll 中,并在头文件中定义它,如下所示:
静态池全局池;
我确实可以从每个 dll 进行访问,但是这个池被创建了很多次。
我认为它发生在我的每个 DLL 和每个包含带有定义的头文件的文件中。
我怎样才能正确地做到这一点? 谢谢 :)
I have a C++ windows application which is composed of several DLLs.
I want to have some sort of a pool from which I'll get objects, but in a way that this pool
would be available in all the DLLs.
So I put it in a "Common" dll which everbody has access to and defined it in a header file like so:
static Pool globalPool;
I do have access from every dll but this pool is created many many times.
I think it happens in each of my DLLs and in each File which include the header file with the definition.
How can I do it properly?
thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对象的静态声明使该对象成为编译单元的本地对象。
通过使用
static
,您可以在包含标头的每个编译单元中创建一个globalPool
对象(变量)。但做你想做的事情的方法不仅仅是删除
static
。相反,定义一个提供对池的访问的函数(例如对其的引用),并从池 DLL 中导出该函数或函数集。
或者更好——更好更好——忘记这个想法。这通常是个坏主意。但是,如果您真的想这样做,并且看不到任何替代方案,那么上面就是如何做到这一点。
如果你这样做,也许要考虑一下线程安全。
也许要注意,Windows DLL 的动态加载与编译器对线程局部变量的支持不能很好地配合。
干杯&呵呵,
A
static
declaration of an object makes the object local to the compilation unit.By using
static
you're creating aglobalPool
object (variable) in every compilation unit where you include the header.But the way to do what you want is not to just remove the
static
.Instead define a function providing access to your pool (e.g. a reference to it), and export that function or set of functions from the pool DLL.
Or better -- much better -- forget the idea. It's a generally bad idea. However, if you really want to do it, and can't see any alternative, then above is how to do it.
And if you do that, perhaps think about thread safety.
And perhaps be aware that dynamic loading of Windows DLLs does not work well with compiler support for thread local variables.
Cheers & hth.,
在你需要的头文件中
然后在Common dll中的.cpp文件中,你需要
extern 声明将其放在包含模块的命名空间中,链接器将其解析为common dll中的对象。
In the header file you need
Then in a .cpp file in the Common dll, you need
The extern declaration will put it in the namespace of including modules, and the linker will resolve it to the object in the common dll.
您需要一个如下所示的头文件:(
有关
dllimport
和dllexport
内容的更多信息,请参阅 http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx 和 http://msdn.microsoft.com/en-us/library/81h27t8c.aspx)然后在在您的 DLL 构建中,您将需要一个如下所示的源文件:
然后,所有使用它的 DLL 和 EXE 都应该
"#include Common.h"
并与 Common DLL 链接,然后它们就可以使用Pool::data1
等You'll want a header file that looks something like this:
(For more about the
dllimport
anddllexport
stuff, see http://msdn.microsoft.com/en-us/library/3y1sfaz2.aspx and http://msdn.microsoft.com/en-us/library/81h27t8c.aspx)Then in your DLL's build, you will want a source file like this:
Then, all the DLLs and EXEs that use it should
"#include Common.h"
and link with the Common DLL, and then they can usePool::data1
, etc.