Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit vs. Explicit linking to a DLL

When one should implicitly or explicitly link to a DLL and what are common practices or pitfalls?

like image 301
Shinnok Avatar asked Jan 25 '11 13:01

Shinnok


3 Answers

It is fairly rare to explicitly link a DLL. Mostly because it is painful and error prone. You need to write a function pointer declaration for the exported function and get the LoadLibrary + GetProcAddress + FreeLibrary code right. You'd do so only if you need a runtime dependency on a plug-in style DLL or want to select from a set of DLLs based on configuration. Or to deal with versioning, an API function that's only available on later versions of Windows for example. Explicit linking is the default for COM and .NET DLLs.

More background info in this MSDN Library article.

like image 124
Hans Passant Avatar answered Nov 07 '22 00:11

Hans Passant


I agree with other who answered you already (Hans Passant and shoosh). I want add only two things:

1) One common scenario when you have to use LoadLibrary and GetProcAddress is the following: you want use some new API existing in new versions of Windows only, but the API are not critical in your application. So you test with LoadLibrary and GetProcAddress whether the function which you need exist, and use it in the case. What your program do if the functions not exist depend total from your implementation.

2) There are one important options which you not included in your question: delayed loading of DLLs. In this case the operating system will load the DLL when one of its functions is called and not at the application start. It allows to use import libraries (.lib files) in some scenarios where explicitly linking should be used at the first look. Moreover it improve the startup time of the applications and are wide used by Windows itself. So the way is also recommended.

like image 25
Oleg Avatar answered Nov 07 '22 00:11

Oleg


I'm assuming you refer to linking using a .lib vs loading a DLL dynamically using LoadLibrary().

Loading a DLL statically by linking to its .lib is generally safer. The linking stage checks that all the entry points exist in compile time and there is no chance you'll load a DLL that doesn't have the function you're expecting. It is also easier not to have to use GetProcAddress().

So generally you should use dynamic loading only when it is absolutely required.

like image 21
shoosh Avatar answered Nov 07 '22 00:11

shoosh