October 3rd, 2025
0 reactions

Can we get weak functions for static linking? The Visual C++ compiler says “We have weak functions at home”

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.

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

0 comments