Static linking & dynamic linking of DLLs with simple example in C++ win32

Hi
I need to know what is Static linking & dynamic linking of DLLs with simple example in C++ win32.
Where it'd be useful?
How to decide what to use.

Thanks
Subrat
LVL 9
Subrat (C++ windows/Linux)Software EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

evilrixSenior Software Engineer (Avast)Commented:
>> I need to know what is Static linking & dynamic linking of DLLs
Static linking to a DLL is when you link to a .lib file that contains stub function for the DLL and at runtime it will implicitly load the DLL for you. Dynamic linking is where you have no compile time dependency on any library and you use the LoadLibrary() to load the DLL at runtime

LoadLibrary()
http://msdn.microsoft.com/en-us/library/ms684175.aspx

Linking implicitly
http://msdn.microsoft.com/en-us/library/d14wsce5.aspx

Linking explicitly
http://msdn.microsoft.com/en-us/library/784bt7z7.aspx

This MSDN help explains all you need to know about linking to DLLs
http://msdn.microsoft.com/en-us/library/9yd93633.aspx
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
softbeeCommented:
More appropriately known as early and late binding, the 2 mechanisms are totally different.
For early binding it is required that you have the dll, its .lib file and its .h file available. The header and library files are then included in your own project and, if the header file is set up correctly, you should be able to call the functions in the library at will.
For late binding you need none of the details of the the library but you MUST know the exact construction of each of the functions you are going to use, which essentially means the the header file or proper documentation of the library is required.
The code snippet below will show a practical example of late binding.

You should however get a decent grip on the theory involved and for this you could use MSDN or a good book on the subject.

As to which is used when, the answer is less obvious.
If the development languages are the same and you have all that is needed then early binding is the obvious answer.
If for instance, you are developing a COM object and the COM object needs information from a DLL that was written using MFC, AND the COM object is used from .Net, then your only way out is late binding, since it isolates the components from its other.
typedef INT (CALLBACK* FUNCADR)(LPTSTR, LPTSTR, LPTSTR, LPTSTR);
 
HINSTANCE hDLL;           // Handle to DLL
FUNCADR lpFuncAdr;		  // Function pointer
 
hDLL = LoadLibrary("dyseutil");
if (hDLL != NULL)
{
	lpFuncAdr = (FUNCADR)GetProcAddress(hDLL, "dllImageClip");
	if (!lpFuncAdr)
	{
		// handle the error
		// <winerror.h>
		DWORD e = GetLastError();
		CString strMsg;
		strMsg.Format("dllImageClip entry NOT Found. Err = %d", e);
		FreeLibrary(hDLL);
	}
	else
	{
	         char szMsg1[255] = {""};
		char szMsg2[255] = {""};
		char szMsg3[255] = {""};
		char szMsg4[255] = {""};
 
		int intRes = 0;
		// call the function
		intRes = lpFuncAdr(szMsg1, szMsg2, szMsg3, szMsg4);
		FreeLibrary(hDLL);
 
		ClipQty = intRes;
 
		CString strMsg;
		strMsg.Format(_T("DYSEUTIL result is %d:\n"),intRes);
			AfxMessageBox(strMsg);		
		}
	}
	else
          	AfxMessageBox(_T("LoadLibrary DYSEUTIL failed"));

Open in new window

0
evilrixSenior Software Engineer (Avast)Commented:
>> More appropriately known as early and late bindingHmmm... in C++ early and late binding have a specific meaning to do with how virtual functions and polymorphism is implemented, I'm not sure I've ever heard the term use in relation to static and dynamic linking. I would argue that static/dynamic linking could be used to implement a form of early/late binding but I'm not sure I'd consider either a specific example of this.http://www.learncpp.com/cpp-tutorial/124-early-binding-and-late-binding/Please do feel free to prove me wrong though :)
0
C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

softbeeCommented:
evelrix,
Your comment is perfectly legal. I retract the use of the terminology.
Thanks for the tutorial, I have been using the principles for nearly 20 years, but it is good to re-read why you were doing things the way you were doing it.
Do you agree with the example though?
0
HooKooDooKuCommented:
Perhaps I'm really old school, but I read the question as...
What is the difference between
1. Static linking, and
2. Dynamic linking (with the words DLL being redundant).

In that case, static linking is when the object code of a library of functions is permenently linked to the executable and the object code of the library is included in the executable.
But dynamic linking is when the object code resides in an external file and the executable doesn't make the final link to the library object code until runtime.
So with dynamic linking, you can swap out object code for the library functions so long as the interface between the executable and the library remain unchanges.  But with static linking, the link is permenent and you can not change the library object code without rebuilding the executable.
One of the plusses of using static linking is that you don't have to insure the dlls are available to the executable, and it should be faster loading the application (however with the speed of modern computers, that isn't as much an issue).  But the negative of using static libraries is that you also duplicate the object code in each executable.  With dynamic linking, you have only one copy of the object code that multiple executables can used.

To me, static linking is when the object code of a library of functions are included within the executable and therefore the executable is staticlly linked to the object code.
Dynamic linking, on the other hand, is when the object code of a library of functions exist inside a DLL and the executable is simply linked to function stubs.  Then at run time, the link to the object code is finalized.

Stated another way, Static linking is when the
 and get linkthe difference is where the library of functions exist after the link process.  If the library code in included within the executable, then the executable is statically linked to the library code. has been statically linked to the that static linking is when you link to a set of library functions that get included in your add a set of library functions into the executable get compiled and added to the exe at compile time
0
evilrixSenior Software Engineer (Avast)Commented:
>> Perhaps I'm really old school
>> with the words DLL being redundant
The words DLL are NOT redundant, Microsoft provide to distinct ways to link to a DLL. You can statically (implicit) or dynamically (explicit) link to a DLL. The difference is important to understand and goes well beyond just the semantic differences of linking to a .lib or a DSO (dynamic shared object).

>> Dynamic linking, on the other hand, is when the object code of a library of functions exist inside a DLL and the executable is simply linked to function stubs.
That is static linking and NOT dynamic linking because you are building in a compile time dependency on the DLL. You link to a .lib function stub library and from that point on you are bound at a binary level to that DLLs interface. Dynamic linking is using LoadLibrary to dynamically load the DLL at runtime, there is no compile time dependency (the don't even need access to the DLL to compile the code). Also, the DLL doesn't have to exist, the code can handle failure to load the DLL and keep running, with a statically linked DLL this is not possible.

Did you read the links I posted? They will explain this all in much detail and I'm sure after reading it you'll see what the differences are more clearly.
0
HooKooDooKuCommented:
>>The words DLL are NOT redudant...
>>That is static linking and NOT dynamic linking
Like I tried to explain, I first learned programming in the days when Microsoft was a company the made a product known as MS-DOS, and we programmed on mini-computers, and PCs were a thing of the future.
Back then, the difference between a static library and dynamic library was where the library object code lived after the link step.  Back then, when you staticly linked to a library, you included the object code of the library in your executable.  Dynamic libraries were when the library object code lived in a DLL file outside of the executable.

>>Did you read the links I posted?
Those links to not address STATIC linking v. DYNAMIC linking.  The all talk about various forms of linking to a DLL.  I'm trying to point out (again, at least in the old school where I learned programming) that static vs dynamic linking delt with where the library object code lived after the link step.  In the case of static linking, the object code is included with the executable.  In the case of dynamic linking, the object code lives outside the executable.

Additionally, early binding v. late binding have also been talked about within this question.  To me, that is a totally seperate issue and has nothing to do with static linking (of libarary code to an exacutable) vs dynamic linking (of library code to an exacutable) because you can have early and late bindings with static and dynamic libraries.  In other words, early v late binding is a discussion of how the logic flows  (which function attually gets called).  But static and dynamic linking has to do with how the object code of a library is connected to the rest of the executable.

As an example, with MFC, you can link to MFC either statically (where the MFC code gets included in your executable) or dynamically (where MFC code resides in DLLs your executable links to at runtime).  But I think the reason for why my "old school" definision seems to be different from everyone elses is that with modern operating systems, the whole operating system is built with DLLs, and therefore any code that has been compiled to run against that operating system is going to have dynamic link libraries.  This is different from the days when I worked on mini-computers when ALL of the object code that executed was contained in the final executable.  So even in today's world where you can choose to link to MFC as a static library or a dynamic library, even when you link to MFC as a static library, that library itself is linked to DLLs of the operating system.
0
evilrixSenior Software Engineer (Avast)Commented:
HooKooDooKu, you are ignoring the context of the question, it is specifically to do with the difference of static vs. dynamic linking to a DLL. "I need to know what is Static linking & dynamic linking of DLLs". The links I post above, to the MSDN that explain in detail the difference, Do address "STATIC linking v. DYNAMIC linking" within this context. That is the purpose of those pages. :)

>> Those links to not address STATIC linking v. DYNAMIC linking.  The all talk about various forms of linking to a DLL.
Exactly, either static or dynamic... which is what this Q is about.

>>  I'm trying to point out (again, at least in the old school where I learned programming)
But that is NOT what the asker has asked to be explained and, as such, you are probably confusing the issue.

By all means contribute to a question but please keep it to answering the question not giving a sermon of back in the old days... that doesn't really help anyone.
0
HooKooDooKuCommented:
As I tried to point out, my (quite possibly incorrect) interpretation of the question is:
"I need to know what is Static linking & dynamic linking" (with DLL being redundant, because what else would you dynamically link to".

Everyone else is interperting the question as:
"I need to know what is Static linking [of DLLs] & dynamic linking of DLL's".

As a concept, I personally have never heard of "Static linking of DLLs" because as best as I knew, you always statically link to DLL stub functions but that's still dynamic linking.

IF I am right (and I obviously might be wrong in MY interpretation of the question) then my comments are totally appropriate.

If I am wrong, then I'm learning a new concept, that you can statically or dynamically link to a DLL.

Or everyone might be a little confused regarding symantics here (after all, why did the subject of early binding and late binding come into play with a subject of static linking verses dynamic linking when the two subjects are completely different).
0
HooKooDooKuCommented:
BTW, I reviewed the above links to MSDN, and the word "static" is only present in sample code (i.e. the C 'static' key word) or in the following statements:

Implicit linking is sometimes referred to as static load or load-time dynamic linking.
Explicit linking is sometimes referred to as dynamic load or run-time dynamic linking.

No where does anything in those pages use the words "static linking", only static loading.  Hence the reason I think everyone else might be misinterpreting the question since is specifically states "static linking" and NOT "static loading".

0
evilrixSenior Software Engineer (Avast)Commented:
>> "I need to know what is Static linking & dynamic linking" (with DLL being redundant, because what else would you dynamically link to

Without the Word DLL in the sentence you could then ligitimately discuss the difference between linking to object files, static libraries and DSOs (dynamic shared objects) but the addition of DLL makes the question very clear.

>> Everyone else is interperting the question as:"I need to know what is Static linking [of DLLs] & dynamic linking of DLL's".

Because that is what it says, only you are chosing to reword the question :)

>> If I am wrong, then I'm learning a new concept, that you can statically or dynamically link to a DLL.

Like I said, read the links I posted, yes you can do both with a DLL (although the overall semantics are still that of dynamic linkage).

>> Or everyone might be a little confused regarding symantics here

I assure you I am 100% clear :)

>> why did the subject of early binding and late binding come into play
Because softbee was confused, see his follow-up post where he states, "Your comment is perfectly legal. I retract the use of the terminology"

>> since is specifically states "static linking" and NOT "static loading".
But it is the mechanics of linking to a static stub library or not (and using LoadLibrary instead) that define the
difference, hence you can static link to a DLL.

http://msdn.microsoft.com/en-us/library/d14wsce5.aspx

To implicitly link to a DLL, executables must obtain the following from the provider of the DLL:

- A header file (.h file) containing the declarations of the exported functions and/or C++ classes. The classes, functions, and data should all have __declspec(dllimport), for more information, see dllexport, dllimport.

- *** An import library (.LIB files) to link with. (The linker creates the import library when the DLL is built.) ***

- The actual DLL (.dll file).

Anyway, at the risk of polluting this thread I'd really rather leave it at that now. The asker has much information here to digest and if anything needs further clarification I'm sure he or she will ask.

Thanks HooKooDooKu.
0
Subrat (C++ windows/Linux)Software EngineerAuthor Commented:
Hi all,
Thanks for your response. But I didn't find Where it'd be useful?
How to decide what to use.(give me some  real time example if possible)
0
softbeeCommented:
Already done.
0
evilrixSenior Software Engineer (Avast)Commented:
>> How to decide what to use.(give me some  real time example if possible)
Using static linking is simpler, so if you don't expect your interfaces to change often and you just want to use the DLL without jiggery-pokery then you'd probably use static linking. If the DLL interfaces change often, or you want to support multiple versions you'd probably consider using dynamic since you can make runtime decisions when attempting to load the DLL. Also, dyanmic linking is useful if you want to support plugins. You can parse a specific path for all the DLLs there, for example, and attempt to load them and then check if they support a specific interface and if they do then use it.

The static loading mechanism is really about convenience but you sacrifice flexibility, whereas the dynamic loading mechanism requires much more work but is very flexible.
0
philrosenbergCommented:
When you static link you include all dlls (which includes either code from the C++ libraries or libraries you've written yourself) directly into your .exe (assuming windows) when you compile it. When you dynamically link you write a bit of code that looks for the dll when you run your exe.
This means that when you put your exe on another computer you have to transfer all the relevant dlls too. However there is an advantage. If you need to update a function in a dll then you can just supply a new version of the dll - you don't need to recompile the exe and supply a whole new version.
There is a good dll tutorial at http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/article.php/c9855

When using msvc++ you can change from static to dynamic properties by going to configuraton properties, C/C++, Code Generation. Some details of how to work out which dlls to redistribute with your app are at http://msdn.microsoft.com/en-us/library/ms235299(vs.80).aspx
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.