Shared global variable in C++ static library(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++静态库中的共享全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++静态库中的共享全局变量
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
