from :http://www.cnblogs.com/skynet/p/3372855.html

C++ Static library and dynamic library

This time I shared Purpose yes —— Let us learn to create and use static library 、 Dynamic library , Know the difference between static library and dynamic library , Know how to choose when using . I won't go into static libraries here 、 The underlying format of the dynamic library , Memory layout, etc , Interested students , Recommend a Book 《 Self cultivation of programmers —— link 、 Loading and storage 》.

What is a library

The library is written out of the existing , ripe , Reusable code . In reality, every program depends on a lot of underlying libraries , It's impossible for everyone's code to start from scratch , So the significance of the existence of the library is extraordinary .

Essentially, a library is a binary form of executable code , Can be loaded into memory by the operating system for execution . There are two kinds of libraries. : Static library (.a、.lib) Dynamic library (.so、.dll).

Static 、 Dynamic is about links . Take a look back. , The steps of compiling a program into an executable :

chart : The build process

Static library

What makes it 【 Static library 】, Because in the link phase , Will assemble the generated target file .o Link and package to executable file together with the referenced Library . Therefore, the corresponding link mode is called static link .

Just imagine , The static library is linked to the assembly generated target file as an executable , So the static library must follow .o The file format is similar . In fact, a static library can be simply seen as A set of target files (.o/.obj file ) Set , That is, many target files are compressed and packaged to form a file . Summary of static library features :

l  The link between static library and function library is completed at compile time .

l  The program has nothing to do with the function library at runtime , Transplant convenience .

l  Waste space and resources , Because all related target files and related function libraries are linked to form an executable file .

Now write some simple four operations C++ class , Compile it into a static library for others to use , The header file is as follows :

StaticMath.h The header file

#pragmaonce

classStaticMath

{

public:

    StaticMath(void);

    ~StaticMath(void);

 

    staticdouble add(double a, double b);// Add

    staticdouble sub(double a, double b);// Subtraction

    staticdouble mul(double a, double b);// Multiplication

    staticdouble div(double a, double b);// division

 

    void print();

};

Linux Next use ar Tools 、Windows Next vs Use lib.exe, Compress the target files together , And number and index them , To facilitate the search and retrieval of . The steps to create a static library are shown in the figure :

chart : Create static library process

Linux Create and use static libraries

Linux Static library naming rules

Linux Static library naming conventions , Must be "lib[your_library_name].a":lib The prefix , In the middle is the static library name , extension .a.

Creating a static library (.a)

You can know through the above process ,Linux The process of creating a static library is as follows :

l  First , Compile the code file into the target file .o(StaticMath.o)

g++ -c StaticMath.cpp

Pay attention to the parameters -c, Otherwise, compile it directly as an executable

l  then , adopt ar The tool packages the target file into .a Static library files

ar -crv libstaticmath.a StaticMath.o

Generate static libraries libstaticmath.a.

Larger projects will be written makefile file (CMake And engineering management tools ) To generate static libraries , It's too much trouble to enter multiple commands .

Use static libraries

Write the test code using the static library created above :

Test code :

#include"StaticMath.h"

#include<iostream>

usingnamespace std;

 

int main(intargc, char* argv[])

{

    double a = 10;

    double b = 2;

 

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

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

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

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

 

    StaticMath sm;

    sm.print();

 

    system("pause");

    return 0;

}

Linux Use static library under , Just need to compile , Specify the search path for the static library (-L Options )、 Specify the static library name ( Unwanted lib The prefix and .a suffix ,-l Options ).

# g++ TestStaticLibrary.cpp -L../StaticLibrary -lstaticmath

l  -L: Indicates the directory of the library to connect to

l  -l: Specify the dynamic library needed when linking , There are implicit naming rules when the compiler looks up the DLL , I.e. add... Before the given name lib, Followed by .a or .so To determine the name of the library .

Windows Create and use static libraries

Creating a static library (.lib)

If using VS The command line generates static libraries , There are two steps to generate the program :

l  First , By using the compiler option  /c  Of  Cl.exe  Compile code (cl /c StaticMath.cpp), Create a “StaticMath.obj” The target file of .

l  then , Using the library manager  Lib.exe  Link code (lib StaticMath.obj), Creating a static library StaticMath.lib.

Of course , We don't usually use this , Use VS The project setting is more convenient . establish win32 Console program , Check the static library type ; Open the project “ Property panel ”è” Configuration properties ”è” routine ”, Configuration type select static library .

chart :vs Static library project property settings

Build Project can generate static library .

Use static libraries

How to use :

Method 1 :

stay VS Use static methods in the library :

l  engineering “ Property panel ”è“ General properties ”è “ Frames and references ”è” Add reference ”, Will be displayed “ Add reference ” Dialog box . “ project ” The tab lists the projects in the current solution and all libraries that can be referenced . stay “ project ” Tab , choice StaticLibrary. single click “ determine ”.

l  add to StaticMath.h Header Directory , The include directory path must be modified . Open the project “ Property panel ”è” Configuration properties ”è “C/C++”è” routine ”, stay “ Attach include directory ” Property value , type StaticMath.h The path of the directory where the header file is located or browse to the directory .

Compile operation OK.

chart : Static library test results (vs)

The method settings in the .

Method 2 :

Open the project “ Property panel ”è” Configuration properties ”è “ The linker ”è” Command line ”, Enter the full path of the static library .

Method 3 :

l  “ Property panel ”è” Configuration properties ”è “ The linker ”è” routine ”, Input... In the directory of additional dependency library , The directory where the static library is located ;

l  “ Property panel ”è” Configuration properties ”è “ The linker ”è” Input ”, Input static library name in additional dependency library StaticLibrary.lib.

Dynamic library

Discover static libraries through the above introduction , Easy to use and understand , It also achieves the purpose of code reuse , So why do we need dynamic libraries ?

Why do we need dynamic libraries ?

Why dynamic libraries are needed , In fact, it is also the characteristics of the static library .

l  Space waste is a problem with static libraries .

l  Another problem is the static library to update the program 、 Trouble deploying and publishing pages . If the static library liba.lib Updated , So applications that use it all need to be recompiled 、 Publish to users ( For players , It could be a small change , It causes the whole program to download again , Full update ).

Dynamic libraries are not connected to the target code when the program is compiled , It's loaded when the program is running . Different applications call the same library , Only one instance of the shared library is needed in memory , Avoid the problem of space waste . Dynamic library is loaded when the program is running , It also solves the update of static library to program 、 Trouble deploying and publishing pages . Users only need to update the dynamic library , Incremental updating .

Summary of dynamic library features :

l  Dynamic libraries delay the loading of links to some library functions until the program runs .

l  It can realize resource sharing among processes .( So dynamic libraries are also called shared libraries )

l  Make it easy to upgrade some programs .

l  It can even be true that link loading is completely controlled by the programmer in the program code ( Display call ).

Window And Linux Execution file format is different , There are some differences in creating dynamic libraries .

l  stay Windows The format of the execution file under the system is PE Format , Dynamic library needs a DllMain Function to make the entry of initialization , Usually, when exporting the declaration of a function, you need to _declspec(dllexport) keyword .

l  Linux Next gcc The compiled execution file defaults to ELF Format , There is no need to initialize the entry , There is no need for a function to make a special declaration , It's easy to write .

Unlike creating a static library , No packing tools needed (ar、lib.exe), Use the compiler directly to create dynamic libraries .

Linux Create and use dynamic library

linux Naming rules for dynamic libraries

The name of the DLL is in the form of libxxx.so, The prefix is lib, Suffix named “.so”.

l  For the actual library file , 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 .

l  In the file system ,soname It's just a link to the actual dynamic library . For dynamic libraries , Each library actually has a different name for the compiler to use . It's a link to the actual library image file (lib+soname+.so).

Create a dynamic library (.so)

Write four operation dynamic library code :

DynamicMath.h The header file

#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();

};

l  First , Generate target file , In this case, the compiler option should be added -fpic

g++ -fPIC -c DynamicMath.cpp

-fPIC Create an address independent compiler (pic,position independent code), Is to be able to share between multiple applications .

l  then , Generate dynamic library , In this case, you need to add the linker option -shared

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

-shared Specify to generate DLL .

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

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

Using dynamic libraries

Write test code using dynamic library :

Test code :

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

 

#include <iostream>

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 dynamic library to compile executable file ( Just like static library ):

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

And then run :./a.out, It turns out that the report is wrong !!!

Maybe you'll guess , Because the dynamic library and the test program are not the same directory , Let's see if it's true :

Find or report a mistake !!! that , How to locate the shared library file during execution ?

1)        When the system loads executable code , Be able to know the name of the library it depends on , But you need to know the absolute path . At this point, the system dynamic loader is needed (dynamic linker/loader).

2)        about elf Format executable program , By ld-linux.so* To complete , It searches for elf Of documents DT_RPATH paragraph — environment variable LD_LIBRARY_PATH—/etc/ld.so.cache File list —/lib/,/usr/lib The directory finds the library file and loads it into memory .

How to get the system to find it :

l  If installed in /lib perhaps /usr/lib Next , that ld By default, you can find , No other operations required .

l  If installed in another directory , It needs to be added to /etc/ld.so.cache In file , Steps are as follows :

n  edit /etc/ld.so.conf file , Add the path to the directory where the library file is located

n  function ldconfig , This command will rebuild /etc/ld.so.cache file

We copy the created dynamic library to /usr/lib below , Then run the test program .

Windows Create and use dynamic library

Create a dynamic library (.dll)

And Linux comparison , stay Windows It's a little troublesome to create a dynamic library under the system . First , Need one DllMain Function to make the entry of initialization ( establish win32 Console program , Check DLL Type will automatically generate this file ):

dllmain.cpp Entrance file

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

#include"stdafx.h"

 

BOOLAPIENTRY DllMain( HMODULEhModule,

                       DWORD  ul_reason_for_call,

                       LPVOIDlpReserved

                     )

{

    switch (ul_reason_for_call)

    {

    caseDLL_PROCESS_ATTACH:

    caseDLL_THREAD_ATTACH:

    caseDLL_THREAD_DETACH:

    caseDLL_PROCESS_DETACH:

        break;

    }

    returnTRUE;

}

Usually, when exporting the declaration of a function, you need to _declspec(dllexport) keyword :

DynamicMath.h The header file

#pragmaonce

classDynamicMath

{

public:

    __declspec(dllexport) DynamicMath(void);

    __declspec(dllexport) ~DynamicMath(void);

 

    static__declspec(dllexport) double add(double a, double b);// Add

    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 a dynamic library, you need to set the project properties , Open the project “ Property panel ”è” Configuration properties ”è” routine ”, Configuration type selection dynamic library .

chart :v Dynamic library project property settings

Build Project can generate dynamic library .

Using dynamic libraries

establish win32 Console test program :

TestDynamicLibrary.cpp The test program

#include"stdafx.h"

#include"DynamicMath.h"

 

#include<iostream>

usingnamespace std;

 

int_tmain(intargc, _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 :

l  engineering “ Property panel ”è“ General properties ”è “ Frames and references ”è” Add reference ”, Will be displayed “ Add reference ” Dialog box .“ project ” The tab lists the projects in the current solution and all libraries that can be referenced . stay “ project ” Tab , choice DynamicLibrary. single click “ determine ”.

l  add to DynamicMath.h Header Directory , The include directory path must be modified . Open the project “ Property panel ”è” Configuration properties ”è “C/C++”è” routine ”, stay “ Attach include directory ” Property value , type DynamicMath.h The path of the directory where the header file is located or browse to the directory .

Compile operation OK.

chart : Dynamic library test results (vs)

Method 2 :

l  “ Property panel ”è” Configuration properties ”è “ The linker ”è” routine ”, Input... In the directory of additional dependency library , The directory where the dynamic library is located ;

l  “ Property panel ”è” Configuration properties ”è “ The linker ”è” Input ”, Additional dependency library input dynamic library compiled from DynamicLibrary.lib.

You may have a question here , How can the dynamic library have another DynamicLibrary.lib file ? That is, whether it is a static link library or a dynamic link library , In the end lib file , So what's the difference between the two ? Actually , Two are totally different things .

StaticLibrary.lib The size is 190KB,DynamicLibrary.lib The size is 3KB, Static library corresponding to lib The document is called Static library , Dynamic library corresponding to lib The document is called 【 Import library 】. In fact, the static library itself contains the actual execution code 、 Symbol tables and so on , and For import libraries , The actual execution code is in the dynamic library , The import library only contains the address symbol table and so on , Make sure the program finds some basic address information for the corresponding function .

Explicit calls to dynamic libraries

The dynamic library usage method described above is similar to static library, which belongs to implicit call , When compiling, specify the corresponding library and search path . Actually , Dynamic libraries can also explicitly call .【 stay C In language 】, It's easy to call a dynamic library !

stay Linux Call the dynamic library explicitly

#include <dlfcn.h>, The following interfaces are provided :

l  void * dlopen( const char * pathname, int mode ): Function to open the specified DLL file in the specified mode , And return a handle to the calling process .

l  void* dlsym(void* handle,const char* symbol):dlsym Handle according to DLL (pHandle) And symbols (symbol), Return the address corresponding to the symbol . Using this function, you can not only get the function address , You can also get the variable address .

when , Will be actually unloaded by the system .

l  const char *dlerror(void): When the DLL operation function fails to execute ,dlerror Error messages can be returned , The return value is NULL When the operation function is executed successfully .

stay Windows Call the dynamic library explicitly

The application must make function calls to explicitly load... At run time DLL. For explicit linking to DLL, The application must :

l  call LoadLibrary( Or similar functions ) To load DLL And get module handle .

l  call GetProcAddress, To get a function pointer to each exported function that the application will call . Because the application is called through a pointer DLL Function of , The compiler does not generate external references , So there is no need to link with the import library .

l  Use up DLL After the call FreeLibrary.

Explicit call C++ Dynamic library note

Yes C++ Come on , It's a little more complicated . Explicitly load a C++ The difficulty of dynamic library Part of it is because C++ Of name mangling; The other part is that it didn't provide a suitable API To load classes , stay C++ in , You may want to use a class in the library , This requires creating an instance of the class , It's not easy to do .

name mangling Can pass extern "C" solve .C++ There is a specific keyword used to declare the use of C binding Function of :extern "C" . use extern "C" The declared function will use the function name as the symbolic name , It's like C The function is the same . therefore , Only nonmember functions can be declared as extern "C", And it can't be overloaded . Despite the restrictions ,extern "C" Function is still very useful , Because they can look like C Functions are also dlopen Dynamic loading . Crowned with extern "C" After qualifier , It doesn't mean that... Cannot be used in a function C++ Code. , contrary , It's still a complete C++ function , You can use any C++ Features and various types of parameters .

In addition, how to get from C++ Get class from dynamic library , Attached are several related articles , But I don't recommend it :

l  《LoadLibrary call DLL Medium Class》:http://www.cppblog.com/codejie/archive/2009/09/24/97141.html

l  《C++ dlopen mini HOWTO》:http://blog.csdn.net/denny_233/article/details/7255673

“ Explicit ” Use C++ In dynamic library Class It's a very complicated and dangerous thing , So you can use “ Implicit ” Don't use “ Explicit ”, If you can be static, don't use dynamic .

The attachment :Linux Next library related command

g++(gcc) Compilation options

l  -shared : Specify to generate DLL .

l  -static : Specifies to generate static link libraries .

l  -fPIC : Represents code compiled as location independent , For compiling shared libraries . The target file needs to be created as a location independent code , This is when the executable loads them , They can be placed anywhere in the memory of an executable program .

l  -L. : Indicates the directory where the library to be connected is located .

l  -l: Specify the dynamic library needed when linking . There are implicit naming rules when the compiler looks up the DLL , I.e. add... Before the given name lib, Followed by .a/.so To determine the name of the library .

l  -Wall : Generate all warning messages .

l  -ggdb : This option will generate as much as possible gdb Debugging information that can be used by .

l  -g : Compiler generates information during debugging .

l  -c : Only activate preprocessing 、 Compile and assemble , That is to make the program object file (.o file ) .

l  -Wl,options : Put parameters (options) Pass it to the linker ld . If options There's a comma in the middle , will options Split into multiple options , And pass it to the linker .

nm command

Sometimes you need to see which functions are in a library ,nm command You can print all the symbols involved in the issue . Libraries can be static or dynamic .nm There are many symbols listed , There are three kinds of common :

l  One is called in the library , But it's not defined in the library ( Indicates the need for other libraries to support ), use U Express ;

l  One is the function defined in the library , use T Express , This is the most common ;

l  One is the so-called weak state ” Symbol , Although they are defined in the library , But it may be covered by the same name symbol in other libraries , use W Express .

$nm libhello.h

ldd command

ldd Command to view a shared library that an executable program depends on , For example, the four Operational dynamic libraries we write depend on the following Libraries :

summary

The difference between them is that The code is loaded at different times .

l  Static libraries are linked to the object code at compile time , The static library is no longer needed when the program is running , So it's bigger .

l  Dynamic libraries are not connected to the target code when the program is compiled , It's loaded when the program is running , Therefore, when the program is running, it also needs dynamic inventory in , So the code is smaller .

The advantage of dynamic libraries is , Different applications call the same library , Only one instance of the shared library is needed in memory . While bringing benefits , There will be problems ! Like the classic DLL Hell problem , How to avoid dynamic database management , You can find the relevant information by yourself .

( turn )C++ More articles about static library and dynamic library

  1. C++ series : Static library and dynamic library

    Reprinted from http://www.cnblogs.com/skynet/p/3372855.html The purpose of this sharing is —— Let us learn to create and use static library . Dynamic library , Know the difference between static library and dynamic library , Know how to choose when using ...

  2. C++ Static library and dynamic library

    C++ Static library and dynamic library The purpose of this sharing is -- Let us learn to create and use static library . Dynamic library , Know the difference between static library and dynamic library , Know how to choose when using . I won't go into static libraries here . The underlying format of the dynamic library , Memory layout, etc , Interested students , Recommendation 1 ...

  3. Linux Next Gcc Generate and use static library and dynamic library ( turn )

    One . Basic concepts 1.1 What is a library stay windows The platform and linux There are a lot of Libraries under the platform . Essentially, a library is a binary form of executable code , Can be loaded into memory by the operating system for execution . because windows and linux The platform is different ( ...

  4. Makefile Static library in , The creation and use of dynamic library and decompression command

    The application layer controls the hardware by manipulating files Use the made tool chain : At the beginning of study , Use some toolchains that have been made , Use the following command to unzip to gcc-3.4.5-glibc-2.3.6 Catalog cd /work/tools tar xjf ...

  5. VS in Debug and Realease、 And the difference between static library and dynamic library ( turn )

    Original text :http://www.cnblogs.com/chensu/p/5632486.html One .Debug and Realease The reason for the difference Debug Usually called debug version , It contains debugging information , And not ...

  6. Linux Next C++ Static library 、 The production and use of dynamic library

    Refer to the post :C++ Static library and dynamic library >> Static library 1. The production of static library a) edit name.cpp and name.h file b) $g++ -c name.cpp // Pay attention to the parameters -c, Otherwise, compile directly ...

  7. stay Linux How to use GCC compiler 、 Simple generation Static library and dynamic library

      Recently, I'm writing a Apache  kafka Of C/C++ client ,, Looking at what he wrote  example in , His compiler uses librdkafka++.a and librdkafka.a     Static library compiled ,,, And here we are ...

  8. VS in Debug and Realease、 And the difference between static library and dynamic library

    One .Debug and Realease The reason for the difference Debug Usually called debug version , It contains debugging information , And without any optimization , It's easy for programmers to debug programs .Release It's called a release , It's often optimized , Make the program in code ...

  9. Linux Next Gcc Generate and use static library and dynamic library

    Reference article :http://blog.chinaunix.net/uid-23592843-id-223539.html One . Basic concepts 1.1 What is a library stay windows The platform and linux There are a lot of Libraries under the platform ...

  10. android Development NDK Compiling and using static libraries 、 Dynamic library ( turn )

    stay eclipse Create a jni Folder stay jni Create... In the folder Android.mk and Application.mk file Android.mk file : Android A kind of makefile file , ...

Random recommendation

  1. NoSQL Database classification

    type Some represent characteristic Column store Hbase Cassandra Hypertable seeing the name of a thing one thinks of its function , It stores data in columns . The biggest feature is convenient storage of structured and semi-structured data , Convenient for data compression , For a query on a column or columns, there are ...

  2. ASP.NET One of the programming models ASP.NET Page life cycle diagram

    ASP.NET In programming model ASP.NET What does the page lifecycle mean ? What does it include ?ASP.NET One of the programming models ASP.NET What are the specific processes of page life cycle ? Let's begin our explanation : ASP.NET Page runtime , this ...

  3. sublime install sftp and ctags plug-in unit

    1.  install Package Control plug-in unit  , Installation is done by Sublime Text 2 Console . This is done by pressing Ctrl + ` Quick access . Once opened , Paste the following command to the console . Enter the following python Code subl ...

  4. Java_Activiti5_ Rookies also come to learn Activiti5 workflow _ A simple example of how to get started ( One )

    // VacationRequest.java /** * author : Feng Menghuo ^_^ * dates : 2015 year 9 month 1 Japan Afternoon 10:32:58 * class : Demonstrate a simple company leave process ...

  5. iOS from app Jump to Safari、 from app Turn on the phone call

    1. from app Jump to Safari NSString* strIdentifier = @"http://www.ybyb.com"; BOOL isExsit = [[UIAppli ...

  6. .NET Garbage collection notes

    Noun Garbage collection targets ephemeral GC It happened in Gen 0 and Gen 1 Garbage collection Full GC happen Gen 2 And above Gen And LOH Garbage collection Garbage collection mode Workstation mode GC It happens directly in memory ...

  7. Cocos2d-x Performance analysis -Android Version of Gprof

    stay iOS Under the platform, we can use Xcode Self contained Profile Tools to test the performance of our program ,Android The platform uses gprof Here's a summary of the specific cocos2dx Use gprof A tool for performance analysis ...

  8. [FE] Effectively develop a front-end project 1

    If today's front end is not used npm, Efficiency is relatively low : So in terms of the tools used . 1. Everything depends on nodejs: Download a linux The source code package can be installed . $ wget https://nodej ...

  9. call get_str_time( Time ), You can convert milliseconds into formatted , The way to convert timestamps

    function get_str_time(time){ var datetime = new Date(); datetime.setTime(time); var year = datetime. ...

  10. 9.4、__del__、__doc__、__dict__、__module__、__getitem__、__setitem__、__delitem__、__str__、__repr__、__call__

    Related content : __del__.__doc__.__dict__.__module__.__getitem__.__setitem__.__delitem__.__str__.__repr__.__cal ...