Static link library and dynamic link library

Source: Internet
Author: User
Tags define function

Reproduced:

About the static link library (Lib,. A) with dynamic-link libraries (DLLs,. SO) (2011-10-10 21:04:26) reproduced
Category: C, VC, CPP

Under Windows, you can generally see files with the suffix dll and the suffix Lib, but the two files can be divided into three libraries, namely the dynamic link library (Dynamic-link Libraries), the target library (object Libraries), and the import library Libraries), the following one by one explains these three kinds of libraries.

Target Library (object Libraries)

The target library is also called the Static link library, which is the extension. LIB files, including the user program to use a variety of functions. It is a "static link" to the executable program file when the user program is linked. For example, the most commonly used C run-time target library file in VC + + is LIBC.LIB. The so-called "static Link" method is often used in linked applications to link individual target files (. obj), run-time function libraries (. lib), and compiled resource files (. res) to form an executable (. exe) file. When using static links, the various functions and resources that the executable needs to use are included in the file. The disadvantage of this is that the same functions and resources that are used by multiple programs are repeatedly linked to the EXE file, making the program larger and consuming more memory.

Importing libraries (import Libraries)

The import library is a special form of the target library file. As with the target library file, the extension of the import library file is also. LIB is also a "static link" to an executable file when the user program is linked. However, the import library file does not contain program code. Accordingly, it contains related link information that helps the application establish the correct redirect table for the dynamic link library in the executable file. such as KERNEL32.LIB, USER32. Lib and GDI32.LIB are our common import libraries, and through them we can invoke the functions provided by Windows. If we use the rectangle function in the program, GDI32. Lib can tell the linker that this function is in the GDI32.DLL dynamic link library file. This way, when the user program runs, it knows "dynamic linking" to the GDI32.DLL module to use this function. In fact, the import library is an index, a DLL dynamic link Library Index table, this is my understanding.

Dynamic link library (Dynamic-link Libraries)

Dynamic linking is the organization of some common functions or resources into a dynamic-link library file (. dll), which is mapped to the virtual address space of the calling process, increasing the reference count value of the DLL when a program that needs to use a function or resource in the DLL is started (exactly when it is initialized). Then, when the DLL is actually used, the operating system loads the DLL into memory, and if all programs that use the DLL have ended, the system removes the library from memory. Each process that uses the same DLL shares the DLL's code at run time, but has one copy for the data in the DLL (and, of course, a way to share the data in the DLL). Two functions can be defined in a dynamic-link library: Output functions and intrinsic functions. Output functions can be called by other modules, and intrinsic functions can only be called by the dynamic link library itself. dynamic-link libraries can also output data, but this data is usually used only by its own functions.

As we know, Windows programs are executable files that can create and display one or more forms, using a message loop to receive input from the user. However, dynamic-link libraries cannot be executed directly, and they generally do not receive messages. They are just separate files that contain functions that can be called by Windows programs or other DLLs to accomplish a task.
A "dynamic link" is a function link that Windows programs need to exist in a library at run time. "Static linking" refers to the various object modules (. OBJ), run-time libraries (. LIB) and a resource file (. RES) are linked together to create an executable (. EXE) file.
DERNAL32. Dll,user32. Dll,gdi32. DLLs, various drivers such as KEYBOARD.DRV,SYSTEM.DRV and mouse.drv, graphics cards and printer drivers are all dynamic link libraries. These libraries can be used in conjunction with all Windows programs.
There are some dynamic link libraries (such as font files) called "Resource-only". They include only data, not code. Therefore, one of the purposes of a dynamic-link library is to provide functions and resources for many different programs. In a traditional operating system, the user program can only invoke certain functions of the operating system itself at run time. In the case of Windows operating systems, it is a very common operation for a module or program to invoke a function in another module to execute. Therefore, from a certain point of view, the DLL programming, in fact, the Windows operating system is extended, can also be seen as a user program extension.
A dynamic-link library module can have other extensions, but the standard extension is. Dll. Only dynamic-link library modules with standard extension clauses can be loaded automatically by Windows. In the case of a dynamic-link library module with a different extension, the program must use the LoadLibrary or LoadLibraryEx function to display the load.
We can find that the dynamic link library technology is often used in large-scale application software. For example, if we were to write a large application that included multiple programs. We can see that many processes may use some of the same common functions. We can put these generic functions into a target library file (. LIB), and then the link is to add it to each program for static linking. However, this is a very wasteful approach because each program module includes a separate copy of these common functions. In addition, if we want to change a function in the library file, we must recompile all the programs that use this function. However, if we use the technology of the dynamic link library and put all these common functions into a dynamic link library file, we can solve the various problems mentioned above. First, the dynamic link library keeps only one copy on the hard disk, and the program only calls the functions it uses at run time, so we can save a lot of program storage and running space. Second, if you want to modify a general function, as long as the calling interface does not change, just change its implementation, then we do not have to use each of its programs are recompiled, as long as the dynamic link library module to recompile again.

dynamic-link library modules can also be published as a single product. This allows program developers to use third-party modules to develop their own applications, improve program reuse, and save a lot of time and effort.

Both the target library and the import library are used during program development, and the dynamic link library is used when the program is running. When the program runs, the corresponding dynamic link library file must already be saved on the hard disk. In addition, if you want to use a dynamic-link library file, the file must be saved in the same. EXE file in the same directory, or in the directory specified by the path parameter in the current directory, Windows system directory, Windows directory, or environment variable. The program also follows this order to search for the dynamic link library files it needs.

Create a static link library (LIB)

Creating a static link library is simple, creating a Win32 console program, choosing a static library, where I do not have the option to precompile headers. After the project is generated like the definition of a general function, the definition placed in the header file, and then implemented in the CPP file, the direct build out of a static LIB, the release of a header file to the user can be.

Create a dynamic-link library (DLL)

Create a simple DLL file with the SDK

In VC + + choose to create a new Win32 Dynamic-link Library. It is necessary to create a C + + head file and a C + + source file and join the project. The content in the header file is the declaration of the output function, and the contents of the source file are the definitions of the DllMain function and the output function. Here is one of the simplest examples.

The header file code is as follows:

Code
#ifdef Test_create_dll_exports
#define TEST_CREATE_DLL_API __declspec (dllexport)
#else
#define TEST_CREATE_DLL_API __declspec (dllimport)
#endif

This class is exported from the Test_create_dll.dll
Class Test_create_dll_api Ctest_create_dll {
Public
Ctest_create_dll (void);
Todo:add your methods here.
};

extern Test_create_dll_api int ntest_create_dll;

Test_create_dll_api int fntest_create_dll (void);

When the project is created, Test_create_dll_exports is already defined in the predefined place, generating the export DLL.

The __declspec in header file preprocessing is Microsoft's added "C Extended class Storage attribute" (c Extended storage-class Attributes), which indicates that a given instance is stored as a Microsoft-specific class store property, which can be thread, Naked,dllimport or dllexport. [MSDN Original: The extended attribute syntax for specifying STORAGE-CLASS information uses the __declspec keyword, which specifie s that's instance of a given type is to being stored with a microsoft-specific storage-class attribute (thread, naked, Dllim Port, or dllexport). The output function must be indicated as callback. DllMain is the entry point function of a DLL. You can also not write it. DllMain must return true, otherwise the system terminates the program and pops up a "Error launching Program" dialog box. After compiling the link, get the dynamic link library file Dlldemo.dll and the input library file dlldemo.lib.

_declspec (dllexport)

Declare an export function to say that this function is to be exported from this DLL. I'm going to use it for someone else. Typically used in DLLs.
Omit a way to manually define which functions to export in the Def file. Of course, if your DLL is full of C + + classes, you can't specify the exported function in Def, you can only export the class with __declspec (dllexport).

__declspec (dllimport)

Declaring an import function is to say that the function is imported from another DLL. I'm going to use it. Typically used in an EXE that uses a DLL.
Code can be compiled correctly without using __declspec (dllimport), but using __declspec (dllimport) allows the compiler to generate better code. The compiler is able to generate better code because it can determine whether a function exists in a DLL, which allows the compiler to generate code that skips the level of indirection, which usually appears in function calls across DLL boundaries. However, you must use __declspec (dllimport) to import the variables used in the DLL.

Believe that the person who writes the WIN32 program, has done the DLL, will be very clear __declspec (dllexport) function, it is in order to eliminate in the Def file manually defines which functions to export a method. Of course, if your DLL is full of C + + classes, you can't specify the exported function in Def, you can only export the class with __declspec (dllexport). However, the description of __declspec (dllimport) is a bit strange in the MSDN documentation, so let's take a look at what MSDN says:

Code can be compiled correctly without using __declspec (dllimport), but using __declspec (dllimport) allows the compiler to generate better code. The compiler is able to generate better code because it can determine whether a function exists in a DLL, which allows the compiler to generate code that skips the level of indirection, which usually appears in function calls across DLL boundaries. However, you must use __declspec (dllimport) to import the variables used in the DLL.

extern "C"

Instructs the compiler to name the function with the C language method.

Because of the function overloading of C + + when making DLL export functions, the __declspec (dllexport) function (int,int) is decorate in the DLL, for example, decorate becomes function_int_int, and different compiler decorate methods, resulting in the use of GetProcAddress to obtain a function address inconvenience, when using the extern "C", the above decorate will not occur, because C does not have a function overload, but this is extern " C "modified function, do not have the ability to overload, it can be said that extern and extern" C "is not the same thing.

The C + + compiler will name the exported function when it builds the DLL, and the different compiler will change the rules differently, so the name of the adaptation may not be the same. In this way, if you use different compilers to generate DLLs and client-side code programs that access the DLL, the latter will have problems accessing the DLL's exported functions. To achieve versatility, you need to add qualifiers: extern "C".

However, using the qualifier extern "C" can solve the problem of naming the functions between C + + and C when calling each other, but this method has a flaw, that is, it cannot be used to export the member functions of a class, only to export global functions. LoadLibrary imported function name, for non-adapted functions, can write function names, for the function of the adaptation, it must be @ and the number is written, the same can be loaded successfully, you can try.

Resolve warning Inconsistent DLL linkage

The inconsistent DLL linkage warning is an issue that is often encountered when writing DLLs, and the method for resolving this warning is as follows:

The General Predll_api project relies on whether Mydll_exports is defined to determine if the macro expands to __declspec (dllexport) or __declspec (dllimport). Expansion for __declspec (dllexport) is required for DLL compilation, informing the compiler that the function needs to be exported for external invocation. Expanded to __declspec (dllimport) is used by the caller to inform the compiler that the function is an external import function.

The predefined macros within the project settings are first seen by the compiler. So when the compiler compiles the DLL project MYDLL.cpp, because see the previous project settings have defined Mydll_exports, so the Predll_api expanded to __declspec (dllexport).

The purpose of this is to have the DLL and the caller share the same h file, in the DLL project, the definition of MYDLL_EXPORTS,PREDLL_API is the export; In the project that calls the DLL, the MYDLL_EXPORTS,PREDLL_API is not defined as the import.

Using the static link library (LIB)

Using the static link library requires the library's developers to provide the library's header files and Lib files, generally the Lib file is relatively large (relative to the import library), the static link library is all the instructions are included in the caller generated EXE file, there is no "export a function provided to the user" situation, is either all to , or neither.

Using dynamic-link libraries (DLLs)

Method One: Load-time dynamic linking (implicitly called) (AKA: Static Binding)
Include the DLL's input library file (import Library,.lib file) when you want to invoke the DLL's application link. The specific practice is to add an # include at the beginning of the source file, and then you can call the output file in the Dlldemo.dll in the source file.

#pragma comment (lib, "***.lib")//notifies the compiler DLL of the path and file name of the. lib file, you can also compile the linked application without using the statement, adding the corresponding Lib in the property bar--input--Additional dependencies.

extern "C" __declspec (dllimport) foo (); Declaring an import function

Method Two: Run-time dynamic linking (Explicit invocation) (AKA: Dynamic Binding)
Instead of including the input library file at link time, use LoadLibrary or LoadLibraryEx to load the DLL dynamically in the source program.
The main steps are (take Demodll.dll as an example):

1) typedef function prototypes and define function pointers.
typedef void (callback* Dllfootype) (void);
Dllfootype Pfndllfoo = NULL;
2) load the DLL with LoadLibrary and save the DLL instance handle

HInstance Dllhandle = NULL;
...
Dllhandle = LoadLibrary (TEXT ("Dlldemo.dll"));
3) Use GetProcAddress to get pointers to functions in the DLL
Pfndllfoo = (dllfootype) GetProcAddress (Dllhandle,text ("Dllfoo"));
Note that the pointer returned from GetProcAddress must be transformed to a specific type of function pointer.
4) Check the function pointer and call the function if it is not empty
if (pfndllfoo!=null)
Dllfoo ();
5) Uninstalling the DLL using FreeLibrary
FreeLibrary (Dllhandle);

Advantages of dynamic-link libraries (DLLs)

→ Save memory;
→ Make the application "thinner";
→ You can modify the dynamic link library individually without having to relink with the application;
→ Easy to implement multi-language joint programming (such as using VC + + to write a DLL, and then in VB Call);
→ The resources can be packaged;
→ Can share memory between applications
→......

Static link library and dynamic link library

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.