1. Static link library: It is in the compile time to copy the library code into the project, causing the project to become larger, but faster.
The disadvantage is that a set of code may have multiple copies in memory, consuming memory.
2. Dynamic link library : Libraries are loaded with library code by the WinDOS API with only one copy in memory. Only references that are linked to this code are retained in the project, and there are two dynamic link libraries,
(a) Load time dynamic linking: Automatically loaded when the project runs and automatically unloaded at the end
(b) Run time dynamic linking: Load library functions by calling the LoadLibrary () and GetProcAddress () functions during the project run, unloading with the FreeLibrary () function
Here is an example:
1. Static Library:
Create a static library of Win32 with VS, Project named Libtest, join Lib.h, Lib.cpp
#ifndef lib_h#define lib_hextern "C" int Add (int x, int y); #endif
" Lib.h " int Add (intint y) { return x+y;}
The code is simple and does not explain. Build the LibTest.lib file after compiling.
We need to copy the. lib file and the Lib.h file to the referenced project (or you can specify the. lib file by configuring link)
New Project for reference:
" Lib.h " #pragma comment (lib, "TestLib.lib"); int _tmain (int argc, _tchar* argv[]) { printf ("2+3=%d" , add (23)); while (1); return 0 ;}
The point is
#pragma comment (lib, "TestLib.lib");
2. Dynamic Library:
New project Win32 DLL, name Dlltest, add 3 files, Lib.cpp, Lib.h, Lib.def, code as follows:
//dll.h#ifndef Lib_h#defineLib_hextern "C" int__declspec (dllexport) Add (intXinty);#endif//===================dll.cpp=======================#include"Lib.h"intAddintXinty) { returnx+y;}//---------------------------------dll.def-----------------------------------LIBRARY Dlltest2exportsadd @1
The. def file indicates which functions to export, the name of the exported library. After @ is the function number, preceded by the function name.
Build DllTest.lib, DllTest.dll, where. lib files are used for load time dynamic linking, just like static libraries, providing a reference to a DLL
(1) Run time dynamic linking (as long as the DLL file):
#include <Windows.h>#include<stdio.h>typedefint(*lpaddfun) (int,int);//define a function pointerintMain () {hinstance hdll; the handle of the//dllLpaddfun Addfun;//function pointer variablehDLL= LoadLibrary (TEXT ("DllTest2.dll")); if(hDLL! =NULL) {Addfun= (Lpaddfun) GetProcAddress (hDLL,"Add"); if(Addfun! =NULL) { intresult = Addfun (2,3); printf ("%d", result); } freelibrary (hDLL); } while(1); return 0;}
(2) Load time dynamic linking (both. lib and. dll)
#pragmaComment (lib, "DllTest.lib")extern "C"__declspec (dllimport) Add (intXinty);intMainintargcChar*argv[]) { intresult = Add (2,3); printf ("%d", result); return 0;}
dynamic-link libraries and static-link libraries under Windows