[英]can't define a single object in header accross several DLL
I am using VS2010 on a solution with 2 DLLS and I'm trying to define a global variable to be used across both DLLS. 我在具有2个DLLS的解决方案上使用VS2010,并且试图定义要在两个DLLS之间使用的全局变量。
I have the following code: 我有以下代码:
header.h
namespace A
{
extern DLL_A int myInt;
}
in a a.cpp file in DLL A: 在DLL A中的a.cpp文件中:
#include "header.h"
using namespace A;
DLL_A int A::myInt = 5; //initialisation
in another b.cpp file in DLL A: 在DLL A的另一个b.cpp文件中:
#include "header.h"
using namespace A;
//use myInt for computations in some method, eg myInt++; etc
DLL_A is defined as the usual: DLL_A通常定义为:
#ifdef SOME_DEFINE
# define DLL_A __declspec(dllexport)
# else
# define DLL_A __declspec(dllimport)
# endif
However what happens is that while debugging in b.cpp, I see in the watch window that &A::myInt and &myInt are different, which means that an (unknown) "myInt" variable is used for computations, while A::myInt is correctly initialized to 5. 但是发生的是,在b.cpp中调试时,我在监视窗口中看到&A :: myInt和&myInt不同,这意味着(未知)“ myInt”变量用于计算,而A :: myInt是正确初始化为5。
can someone explain to me what is going on and how to fix this? 有人可以向我解释发生了什么事以及如何解决此问题? I don't see how it's possible to link properly, because I have 2 different extern variables that are created and I only initialise one. 我看不到如何正确链接,因为我创建了2个不同的外部变量,并且只初始化了一个。
edit : 编辑:
if I change 如果我改变
DLL_A int A::myInt = 5; //initialisation
for 对于
DLL_A int myInt = 5; //initialisation
it won't link 它不会链接
thanks 谢谢
You say " I see in the watch window that &A::myInt and &myInt are different, which means that an (unknown) "myInt" variable is used for computations". 您说:“我在监视窗口中看到&A :: myInt和&myInt不同,这意味着(未知)“ myInt”变量用于计算”。
That there is exactly your problem. 那正是你的问题。 using namespace A;
means that an unqualified name such a myInt
will be looked up in A
only after the lookup has failed in the current (ie global) namespace. 意味着只有在当前(即全局)名称空间中查找失败后 ,才会在A
中查找诸如myInt
类的不合格名称。 But the debugger shows that ::myInt
exist. 但是调试器显示::myInt
存在。 Therefore, myInt
means ::myInt
, the first lookup succeeds, and no second lookup is done for ::A::myInt
. 因此, myInt
意味着::myInt
,第一次查找成功,并且::A::myInt
没有第二次查找。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.