title: How to mimic the "multiple instances of global variables within the application" behaviour of a static library but using a DLL?
body: <p>We have an application written in C/C++ which is broken into a single EXE and multiple DLLs.  Each of these DLLs makes use of the same static library (<code>utilities.lib</code>).</p>
  
  <p>Any global variable in the utility static library will actually have multiple instances at runtime within the application.  There will be one copy of the global variable per module (ie DLL or EXE) that <code>utilities.lib</code> has been linked into.</p>
  
  <p>(This is all known and good, but it's worth going over some background on how static libraries behave in the context of DLLs.)</p>
  
  <p>Now my question..  We want to change <code>utilities.lib</code> so that it becomes a DLL.  It is becoming very large and complex, and we wish to distribute it in DLL form instead of <code>.lib</code> form.  The problem is that for this one application we wish to preserve the current behaviour that each application DLL has it's own copy of the global variables within the utilities library.  <strong>How would you go about doing this?</strong>  Actually we don't need this for all the global variables, only some; but it wouldn't matter if we got it for all.</p>
  
  <hr>
  
  <p><strong>Our thoughts:</strong></p>
  
  <ol>
  <li>There aren't many global variables within the library that we care about, we could wrap each of them with an accessor that does some funky trick of trying to figure out which DLL is calling it.  Presumably we can walk up the call stack and fish out the <code>HMODULE</code> for each function until we find one that isn't <code>utilities.dll</code>.  Then we could return a different version depending on the calling DLL.</li>
  <li>We could mandate that callers set a particular global variable (maybe also thread local) prior to calling any function in <code>utilities.dll</code>.  The utilities DLL could then use this global variable value to determine the calling context.</li>
  <li>We could find some way of loading <code>utilities.dll</code> multiple times at runtime.  Perhaps we'd need to make multiple renamed copies at build time, so that each application DLL can have it's own copy of the utilities DLL.  This negates some of the advantages of using a DLL in the first place, but there are other applications for which this "static library" style behaviour isn't needed and which would still benefit from <code>utilities.lib</code> becoming <code>utilities.dll</code>.</li>
  </ol>