简体   繁体   中英

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.

I have the following code:

header.h
        namespace A
        {   
            extern DLL_A int myInt;
        }

in a a.cpp file in DLL A:

#include "header.h"
using namespace A;

DLL_A int A::myInt = 5; //initialisation

in another b.cpp file in DLL A:

#include "header.h"
using namespace A;
//use myInt for computations in some method, eg myInt++; etc

DLL_A is defined as the usual:

#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.

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.

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".

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. But the debugger shows that ::myInt exist. Therefore, myInt means ::myInt , the first lookup succeeds, and no second lookup is done for ::A::myInt .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM