The ELF object file has this thing called “weak functions”. These are functions present in a library that are used by the linker to resolve a symbol only if the main program doesn’t provide a resolution for them.
The Visual C++ compiler doesn’t have “weak functions” in this sense, but that doesn’t mean that equivalent functionality doesn’t exist. It’s there, just under a different paradigm.
You can get the same effect as static linking weak functions by taking advantage of the classical model for linking: You can override a LIB with an OBJ or another LIB.
What you do is you put your fallback definition in a library. When the linker needs the function, it starts by looking in the OBJ files, which are the files provided by the main program. If it’s not found there, then the linker goes through the library files in order, and eventually it finds the definition in your library.
Ta da, you have a function definition in your library which can be overridden by the application.
We used this trick some time ago when we created extension points for unit tests to override functionality.
Bonus chatter: Weak functions for static linking is different from weak functions for dynamic linking. Windows does not support weak functions from dynamically-linked libraries. You can fake it by using delay-load instead.
0 comments
Be the first to start the discussion.