In depth research on C + + static library and dynamic library — dynamic library!

Time:2022-5-10

1、 Dynamic library

Through the introduction of the previous article on static library. It is found that static libraries are easier to use and understand, and also achieve the purpose of code reuse. Why do you need dynamic libraries?

1. Why do you need dynamic libraries?

Why dynamic libraries are needed is actually caused by the characteristics of static libraries.

▶ Waste of space is a problem with static libraries.

 

▶ Another problem is that the static library will bring trouble to the update, deployment and release page of the program. If the static library Liba Lib has been updated, so all applications using it need to be recompiled and released to users (for players, it may be a small change, but the whole program will be re downloaded and fully updated).

The dynamic library is not connected to the object code when the program is compiled, but is loaded when the program is running. If different applications call the same library, only one instance of the shared library is needed in memory, avoiding the problem of space waste. The dynamic library is loaded only when the program is running, which also solves the trouble that the static library will bring to the update, deployment and release page of the program. Users only need to update the dynamic library, which can be updated incrementally.

Summary of dynamic library features:

✪ the dynamic library delays the loading of links to some library functions until the program runs.

✪ resource sharing between processes can be realized. (therefore, dynamic libraries are also called shared libraries)

✪ make it easy to upgrade some programs.

✪ you can even really make the link loading completely controlled by the programmer in the program code (display call).

The format of window and Linux executable files is different, and there are some differences when creating dynamic libraries.

✪ the execution file format under Windows system is PE format. The dynamic library needs an entry for DllMain function initialization. Usually, when exporting the declaration of the function, it needs_ Declspec (dllexport) keyword.

✪ the executable file compiled by GCC under Linux is elf format by default. There is no need to initialize the entry or make special declaration of the function. It is convenient to write.

Different from creating static libraries, dynamic libraries can be created directly by using the compiler without packaging tools (AR, lib. Exe).

 

2. Creating and using dynamic library under Linux

The naming rules of Linux dynamic library are:

The name form of dynamic link library is libxxx So, the prefix is lib and the suffix is “. So”.

✪ for actual library files, each shared library has a special name “soname”. After the program starts, the program uses this name to tell the dynamic loader which shared library to load.

✪ in the file system, soname is only a link to the actual dynamic library. For dynamic libraries, each library actually has another name for the compiler. It is a link file (LIB + soname +. So) to the actual library image file.

 

3. Create dynamic library (. So)

Write four operation dynamic library Codes:

#pragma once

class DynamicMath

{

public:

        DynamicMath(void);

        ~DynamicMath(void);

        static double add(double a, double b);

        static double sub(double a, double b);

        static double mul(double a, double b);

        static double div(double a, double b);

        void print();

};

First, generate the target file and add the compiler option – FPIC

g++ -fPIC -c DynamicMath.cpp

-FPIC creates an address independent compiler (PIC, position independent code) to be shared among multiple applications.

Then, generate the dynamic library, and add the linker option – shared at this time

g++ -shared -o libdynmath.so DynamicMath.o

-Shared specifies to generate a dynamic link library.

 

In fact, the above two steps can be combined into one command:

g++ -fPIC -shared -o libdynmath.so DynamicMath.cpp

 

4. Using dynamic libraries

Write test code using dynamic library:

#include "../DynamicLibrary/DynamicMath.h"

#include 

using namespace std;

int main(int argc, char* argv[])

{

    double a = 10;

    double b = 2;

    cout << "a + b = " << DynamicMath::add(a, b) << endl;

    cout << "a - b = " << DynamicMath::sub(a, b) << endl;

    cout << "a * b = " << DynamicMath::mul(a, b) << endl;

    cout << "a / b = " << DynamicMath::div(a, b) << endl;

    DynamicMath dyn;

    dyn.print();

    return 0;

}

Reference the dynamic library and compile it into an executable file (the same way as the static library):

g++ TestDynamicLibrary.cpp -L../DynamicLibrary -ldynmath

Then run:/ a. Out, I found that the report was wrong!!!

 

You may guess that the dynamic library is not the same directory as the test program. Let’s verify whether this is the case:

 

Find or report an error!!! So, how to locate the shared library file during execution?

1) When the system loads executable code, it can know the name of the library it depends on, but it also needs to know the absolute path. At this point, the system dynamic loader (dynamic linker / loader) is required.

2) For the executable program in ELF format, LD Linux So * to complete, it successively searches DT of ELF file_ Rpath segment – environment variable LD_ LIBRARY_ PATH—/etc/ld. so. Cache file list – / lib /, / usr / lib directory. Find the library file and load it into memory.

——————————

How to make the system find it:

✪ if it is installed under / lib or / usr / lib, LD can be found by default without other operations.

✪ if it is installed in another directory, it needs to be added to / etc / LD so. In the cache file, the steps are as follows:

Edit / etc so. Conf file, add the path of the directory where the library file is located

2. Run ldconfig, which will rebuild / etc / LD so. Cache file

We copy the created dynamic library to / usr / lib, and then run the test program.

 

 

2、 Creating and using dynamic library under Windows

1. Create dynamic library (. DLL)

Compared with Linux, creating dynamic libraries under Windows system is a little more troublesome. First, you need a DllMain function to make the entry for initialization (when creating a WIN32 console program, checking the DLL type will automatically generate this file):

// dllmain.cpp : Defines the entry point for the DLL application.

#include "stdafx.h"

BOOL APIENTRY DllMain( HMODULE hModule,

                      DWORD  ul_reason_for_call,

                      LPVOID lpReserved

                    )

{

    switch (ul_reason_for_call)

    {

    case DLL_PROCESS_ATTACH:

    case DLL_THREAD_ATTACH:

    case DLL_THREAD_DETACH:

    case DLL_PROCESS_DETACH:

        break;

    }

    return TRUE;

}

It is usually necessary to export the declaration of a function_ Declspec (dllexport) keyword:

#pragma once

class DynamicMath

{

public:

    __declspec(dllexport) DynamicMath(void);

    __declspec(dllexport) ~DynamicMath(void);

    static __ declspec(dllexport) double add(double a, double b);// addition

    static __ declspec(dllexport) double sub(double a, double b);// subtraction

    static __ declspec(dllexport) double mul(double a, double b);// multiplication

    static __ declspec(dllexport) double div(double a, double b);// division

    __declspec(dllexport) void print();

};

To generate the dynamic library, you need to set the project properties. Open the project “property panel” → “configuration properties” → “general”, and select the dynamic library for the configuration type.

 

Build project can generate dynamic library.

 

2. Using dynamic libraries

Create Win32 console test program:

#include "stdafx.h"

#include "DynamicMath.h"

#include 

using namespace std;

int _tmain(int argc, _TCHAR* argv[])

{

    double a = 10;

    double b = 2;

    cout << "a + b = " << DynamicMath::add(a, b) << endl;

    cout << "a - b = " << DynamicMath::sub(a, b) << endl;

    cout << "a * b = " << DynamicMath::mul(a, b) << endl;

    cout << "a / b = " << DynamicMath::div(a, b) << endl;

    DynamicMath dyn;

    dyn.print();

    system("pause");

    return 0;

}

▶ Method 1:

Project “property panel” → “general properties” → “frame and reference” → “Add Reference”, the “Add Reference” dialog box will be displayed.

The projects tab lists the projects in the current solution and all libraries that can be referenced. In the project tab, select dynamic library. Click OK.

 

Add dynamicmath H header file directory, the path containing the directory must be modified. Open the project “property panel” → “configuration properties” → “C / C + + →” general “. In the” additional include directory “property value, type dynamicmath H the path of the directory where the header file is located or browse to it.

 

Compile and run OK.

 

▶ Method 2:

“Property panel” → “configuration properties” → “linker” → “general”, input in the directory of additional dependent library, and the directory where the dynamic library is located;

 

“Property panel” → “configuration properties” → “linker” → “input”, input the dynamic library compiled from the dynamic library in the additional dependency library lib。

 

In depth research on static library and dynamic library — Summary

Combined with the previous static library and the dynamic library in this article, it is concluded that the difference between them is that the code is loaded at different times.

✪ the static library will be connected to the object code when the program is compiled. The static library will no longer be needed when the program is running, so the volume is large.

✪ the dynamic library is not connected to the object code when the program is compiled, but is loaded when the program is running. Therefore, the dynamic inventory is also required when the program is running, so the code volume is small.

The advantage of dynamic library is that if different applications call the same library, there only needs to be an instance of the shared library in memory. While bringing benefits, there will also be problems! For example, for the classic DLL shell problem, you can find relevant information on how to avoid the problem of dynamic library management.

 

Finally, whether you change careers or start learning, advanced can also be, if you want to learn programming~

[noteworthy] myC / C + + programming learning exchange Club[Click to enter]

Q & A, learning and communication, technical discussion, as well as a collection of super many programming resources, and zero based videos are also great~

 

Recommended Today

Serverless extreme flexibility deconstructs the pain points of online game industry

Author Luo song (Xiliu)Source|Alibaba cloud native official account Reading guide: This paper will analyze specific scene cases in order to bring resonance to relevant game development students, and also hope to bring some inspiration to students in non game industry. 1、 Foreword 1. Game customers’ cloud concerns The game industry is a creative and competitive […]