I ran into an interesting problem the other day that I think is worth sharing. Fans of the pluggable factory design pattern, inversion of control, etc will be interested to know that these methods do not work very well when compiled into static libraries. Sounds obvious but what may not be so obvious is why.
I stumbled onto this problem when I changed one of my exe projects to a static library so I could setup two exe’s, one for unit tests, the other for releasing. (Which by the way is a wonderful way to unit test an exe project) Most of my projects these days use some form of inversion of control so I had static variables creating maker classes which would register themselves with the factory. As explained in one of my previous articles here.
When I changed my project to a static library and linked it to a separate exe project my maker classes stopped registering themselves. Why does this happen? Well after a bit of a research I found out that when you link in a static library, the linker only links code into your project that you actually use. All extra code is left uninitialized and put in a corner to sit while the big boss code runs. A very interesting side effect of static linking.
Anyway, to fix this problem in visual studio you need to set “Use Library Dependency Inputs” in Linker options on your exe project. This will make the linker link in all the object files themselves, instead of selectively linking them as needed. I am researching some way to do this per library, because as of right now if you set this it will link ALL libraries like that.
In linux it would seem the option is -z allextract, but I have not tested this one.
If you need your static objects from a static library to be initiated like normal, this should do the trick.


Recent Comments