C++静态库中的共享全局变量 [英] Shared global variable in C++ static library

查看:43
本文介绍了C++静态库中的共享全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 MS C++ 项目(我们称之为项目 A),我目前正在将它编译为静态库 (.lib).它定义了一个全局变量 foo.我还有另外两个单独编译的项目(分别称为 B 和 C),每个项目都将共享静态库 A 链接到其中. B 和 C 都是最终在同一进程中加载​​的 dll.我想在同一进程中在 B 和 C 之间共享来自 A 的 foo 的单个实例:单例.我不知道如何在这里用项目 A 完成单例模式,因为它是分别静态编译到 B 和 C 中的.如果我在 B 和 C 中都将 foo 声明为 extern,我最终会在 B 和 C 中得到不同的实例.使用带有静态 getInstance 方法的标准、简单的单例类模式会导致两个静态 foo 实例化.

I have a MS C++ project (let's call it project A) that I am currently compiling as a static library (.lib). It defines a global variable foo. I have two other projects which compile separately (call them B and C, respectively) and each links the shared static library A in. Both B and C are dll's that end up loaded in the same process. I would like to share a single instance of foo from A between B and C in the same process: a singleton. I'm not sure how to accomplish the singleton pattern here with project A since it is statically compiled into B and C separately. If I declare foo as extern in both B and C, I end up with different instances in B and C. Using a standard, simple singleton class pattern with a static getInstance method results in two static foo instantiations.

当项目 A 被静态编译成 B 和 C 时,有什么办法可以做到这一点?还是必须将 A 设为 DLL?

Is there any way to accomplish this while project A is statically compiled into B and C? Or do I have to make A a DLL?

推荐答案

是的,您必须将 A 设为共享 DLL,否则将其定义为 B 和 C 中的 extern 并静态链接所有三个.

Yes, you have to make A a shared DLL, or else define it as extern in B and C and link all three statically.

这篇关于C++静态库中的共享全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆