Q:

Accessing extern variable in static lib from exe and dll

In my project, I have an exe, a dll and a static lib.  
The dependencies are as follows: 
 exe -> dll -> lib
  |             ^
  |_____________|

The exe depends on both the dll and lib while the dll depends on the lib. 
In libfile.h
struct A {
   A(int i) : x(i) {}
   int x;
};
extern A* ptr;

and in libfile.cpp, I have A* ptr = nullptr;
In exefile.cpp
#include "libfile.h"
__declspec(dllimport) void foo();
int main() {
  ptr = new A(10);
  foo();
  delete ptr;
}

In dllfile.cpp
 #include "libfile.h"
__declspec(dllexport) void foo();
__declspec(dllexport) void foo() { 
    int a = ptr->x; //error, ptr is nullptr 
}

How can I get access to the A* ptr in lib from both the exe and dll without passing it as a function parameter?  I've tried using an interface function in dll to return ptr to exe but the error persists. 

A:

The dll and exe have different memory locations for that ptr.  I'm assuming here that you have ptr declared in the exe otherwise you will get a linking error (i'm looking at this line ptr = new A(10);).  Changing one will not effect the other. 
To "nice" way get around this is to export from the dll a getter and a setter function for ptr (just like you did with foo):
__declspec(dllexport) A* getPtr() { return ptr; }
__declspec(dllexport) void setPtr(A* new_value) { ptr = new_value; }

In the exe just declare getPtr/setPtr as dllimport and use those to interact with the ptr.