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 (utilities.lib
).
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 utilities.lib
has been linked into.
(This is all known and good, but it's worth going over some background on how static libraries behave in the context of DLLs.)
Now my question.. We want to change utilities.lib
so that it becomes a DLL. It is becoming very large and complex, and we wish to distribute it in DLL form instead of .lib
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. How would you go about doing this? Actually we don't need this for all the global variables, only some; but it wouldn't matter if we got it for all.
Our thoughts:
- 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
HMODULE
for each function until we find one that isn'tutilities.dll
. Then we could return a different version depending on the calling DLL. - We could mandate that callers set a particular global variable (maybe also thread local) prior to calling any function in
utilities.dll
. The utilities DLL could then use this global variable value to determine the calling context. - We could find some way of loading
utilities.dll
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 fromutilities.lib
becomingutilities.dll
.