当前位置:网站首页>The difference between static link library and dynamic link library
The difference between static link library and dynamic link library
2022-06-24 10:18:00 【Wanderer001】
Reference resources The difference between static link library and dynamic link library - cloud + Community - Tencent cloud
Catalog
2.2、 take .c Compile the generated .o file
2.3、 from .o File creation .a Static library
2.4、 Use static libraries in your program
2.5、 Generate target program main, And then run
3、 Dynamic library ( Implicit linking )
3.1、 from .o establish .so Dynamic library
3.2、 Use dynamic libraries implicitly
3.3、 Initialization and parsing of dynamic library
1、 Construction and destructor mechanism of dynamic library
2、 Global variable initialization
4、 Dynamic link library ( Explicit links )
4.1、 Important dlfcn.h The header file
4.2、 Load the instance of dynamic link library
4.3、Windows Lower and Linux The following shows the comparison of loading dynamic link libraries
6、 Look at the symbols in the library
7、Linux Next so Export the specified function
1、 Link library overview
Linux There are dynamic and static libraries , Dynamic usually uses .so For the suffix , Static use .a For the suffix . Face and compare the two :
Static link library : When to use , The connector will find the functions required by the program , Then copy them to the execution file , Because this copy is complete , So once the connection is successful , Static libraries are no longer needed .
For dynamic libraries : When a program needs to call a dynamic link library function during operation , The operating system will first view all running programs , See if there is a copy of this library function in memory . If there is , Then let it share that copy ; Only if there is no link to load . While the program is running , The called DLL function is placed somewhere in memory , All programs that call it will point to this code segment . therefore , These codes must use relative addresses , Not the absolute address . At compile time , We need to tell the compiler , These object files are used as dynamic link libraries , So want to use Address independent code (Position Independent Code (PIC)).
There are two ways to load dynamic link libraries : Implicit loading and explicit loading .
Be careful :linux The default operation for connection under is to connect to the dynamic library first , in other words , If both static and dynamic libraries exist , Unless otherwise specified , Connect with dynamic library ( See Part IV of this article ).
2、 Static link library
Let's demonstrate it to you through practical examples , How to compile and use static and dynamic link libraries :
2.1、 Edit test file
Two documents :add.c、 sub.c、add.h 、sub.h and main.c
/*add.h */
#ifndef _ADD_H_
#define _ADD_H_
int add(int a, int b);
#endif
-------------------------------------------------------------------------------------------------
/*add.c*/
#include "add.h"
int add(int a, int b)
{
return a+b;
}
-------------------------------------------------------------------------------------------------
/*sub.h*/
#ifndef _SUB_H_
#define _SUB_H_
int sub(int a, int b);
#endif
-------------------------------------------------------------------------------------------------
/*sub.c*/
#include "add.h"
int sub(int a, int b)
{
return a-b;
}
-------------------------------------------------------------------------------------------------
/*main.c*/
#include <stdio.h>
#include "add.h"
#include "sub.h"
int main(void)
{
printf("1 + 2 =%d\n", add(1, 2));
printf("1 - 2 =%d\n", sub(1, 2));
return 0;
}
-------------------------------------------------------------------------------------------------
2.2、 take .c Compile the generated .o file
gcc -c add.c
gcc -c sub.c
Generated files :sub.o ,add.o
Whether static or dynamic library files , It's all by .o File created .
2.3、 from .o File creation .a Static library
ar crlibmymath.a sub.o add.o
ar: Static function library creation command
-c :create It means
-r :replace It means , Indicates that the currently inserted module name already exists in the library , Replace the module with the same name . If one of several modules does not exist in the library ,ar Display an error message , Does not replace other modules with the same name . By default , New members added at the end of Kuder .
The naming conventions for library files are based on lib start ( Prefix ), Followed by the static library name , With .a For the suffix .
2.4、 Use static libraries in your program
gcc -o main main.c -L. –lmymath
-L Specify the location where the function library will look , Be careful L There is something '.', Indicates to find... In the current directory
-l Then specify the function library name , Among them lib and .a(.so) Omit .
Be careful :-L Is to specify the search location ,-l Specify the name of the library to be operated .
Static library finished , How to use its internal functions ? You only need to include prototype declarations of these common functions in the source program that uses them , And then with gcc The static library name is specified when the command generates the target file ( yes mymath instead of libmymath.a ),gcc The common functions will be connected from the static library to the target file . Be careful ,gcc Prefixes the static library name lib, Then append the extension .a Get the static library file name to find the static library file . In procedure main.c in , We include the header file of the static library add.h and sub.h, And then in the main program main Call the common function directly in add() and sub() that will do .
2.5、 Generate target program main, And then run
./main
1 + 2 = 3
1 - 2 = -1
3、 Dynamic library ( Implicit linking )
3.1、 from .o establish .so Dynamic library
The dynamic library file name specification is similar to the static library file name specification , Also add a prefix to the dynamic database name lib, But its file extension is .so. for example : We will create a dynamic library called mymath, Then the dynamic library file name is libmamath.so. use gcc To create a dynamic library . At the system prompt, type the following command to get the dynamic library file libmamath.so.
gcc -fPIC-o add.o -c add.c
gcc -fPIC-o sub.o -c sub.c
gcc -shared-o libmamath.so add.o sub.o
perhaps :
gcc –c –o add.oadd.c
gcc –c –o sub.osub.c
gcc -shared -fPCI-o libmyhello.so add.o sub.o
here :
-fpic: Generate code location independent code
-shared : Generating shared libraries
3.2、 Use dynamic libraries implicitly
Using a dynamic library implicitly in a program is exactly the same as using a static library , It also includes the prototype declaration of these common functions in the source program that uses them , And then with gcc When the command generates the object file, it indicates the dynamic library name to compile . Let's run gcc Command to generate the target file , Run it again and see the results .
gcc -o main main.c -L. -lmymath
./main
./main: error while loading shared libraries:libmymath.so: cannot open shared object file: No such file or directory
Something went wrong !!!
Look at the error message , It turned out that the dynamic library file could not be found libmyhello.so. The program is running , Will be in /usr/lib and /lib Find the required dynamic library file in the directory . If you find , Load the dynamic library , Otherwise, the program will be terminated with a similar error .
The search path of the dynamic library is in the order of :
1. The dynamic library search path specified when compiling the object code ;
2. environment variable LD_LIBRARY_PATH Specified dynamic library search path ;
3. The configuration file /etc/ld.so.conf The dynamic library search path specified in ;// Just append a line of the full path where the library is located in the file, such as "/root/test/conf/lib" that will do , then ldconfig It's the amendment coming into effect .
4. Default dynamic library search path /lib;
5. Default dynamic library search path /usr/lib.
The solution to this problem :
1. We will document libmyhello.so Copy to directory /usr/lib in :
mv libmyhello.so/usr/lib/
2. take libmyhello.so Copy to executable main Under the same directory of .
Run again :./main
1 + 2 = 3
1 - 2 = -1
succeed ! This further shows that the dynamic library is needed when the program is running .
3.3、 Initialization and parsing of dynamic library
Windows Dynamic library loading under , There are initialization functions and unloading functions to complete library initialization and resource recycling ,linux Of course, it can also be realized , These initialization functions mainly consist of two parts : Construction and destructor mechanism of dynamic library 、 Initialization of global variables of dynamic library .
1、 Construction and destructor mechanism of dynamic library
stay Linux in , Provides a mechanism : When loading and unloading dynamic libraries , You can write some functions , Deal with something corresponding , We call these functions the constructors and destructors of dynamic libraries , The code format is as follows :
void __attribute__ ((constructor)) my_init(void); // my_init Is the custom constructor name
void __attribute__ ((destructor)) my_fini(void); //my_fini Is the name of the custom destructor
When compiling shared libraries , Out of commission "-nonstartfiles" or "-nostdlib" Options , Otherwise, the build and destructor will not execute normally ( Unless you take certain measures ).
Be careful , Arguments to constructor must be empty , The return value must also be empty .
for instance , Dynamic library files a.c The code for is as follows :
void __attribute__((constructor)) my_init(void)
{
printf("init library\n");
}
Compile into a dynamic library :
gcc -fPIC -shared a.c -o liba.so
The main program main.c as follows :
#include<stdlib.h>
#include<stdio.h>
int main()
{
pause();
return 0;
}
compile :
gcc -L./ -la main.c -o main.bin
function main.bin Program :
in other words , Running main when , Finished loading liba.so after , Automatic operation liba.so Initialization function for .
2、 Global variable initialization
① Let's take a look at the following example :
// file name :b1.c
#include<stdlib.h>
#include<stdio.h>
int reti()
{
printf("reti\n");
return 10;
}
int g1=reti(); // g1 It's a global variable
Use GCC Compile it :
gcc -fPIC -shared b1.c -o libb.so
Compile error ! Use G++ Compile it :
g++ -fPIC -shared b1.c -o libb.so
Compile successfully ! so GCC and G++ For this method of initializing global variables , The support is different .
// The main program
// file name :main.c
#include <stdlib.h>
#include <stdio.h>
int main()
{
pause();
return 0;
}
Compile the executable :
gcc -L./ -lb main.c -o main.bin
function main.bin:
This explanation , The process is loading libb.so after , To initialize global variables g1, It will run reti To initialize the g1.
② Let's see another one C++ Example :
// file name :b2.cpp
class Myclass
{
public:
Myclass();
int i;
};
Myclass::Myclass()
{
printf("constructMyclass\n");
};
Myclass g1;
Compile dynamic library :
g++ -fPIC -shared b2.cpp-o libb.so
In the dynamic library libb.so in , Declared a type of Myclass Global variable of g1.
// The main program
// file name :main.cpp
#include <stdlib.h>
#include <stdio.h>
#include<unistd.h>
int main()
{
pause();
return 0;
}
Compile the executable :
g++ -L./ -lb main.cpp -o main.bin
function main.bin:
This explanation , The process is loading liba.so after , To initialize global variables g1, The program is entering main Function will be run before Myclass Constructor for .
4、 Dynamic link library ( Explicit links )
4.1、 Important dlfcn.h The header file
LINUX Use dynamic link library , The source program needs to contain dlfcn.h The header file , This file defines the prototype of the function that calls the dynamic link library . These functions are described in detail below .
function dlerror:
Archetype : 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 .
function dlopen: Open the specified DLL file
Archetype : void *dlopen (const char *filename, int flag);
dlopen Used to open the specified name (filename) Dynamic link library for , And return the operation handle .
filename: If the name doesn't start with / start , Then the non absolute pathname , The file will be found in the following order :
(1) In the user environment variable LD_LIBRARY value ;
(2) Dynamic link buffer file /etc/ld.so.cache
(3) Catalog /lib,/usr/lib
flag Indicates when to resolve undefined symbols ( call ). There are two values :
1) RTLD_LAZY : Indicates that the problem is solved when the function code of the dynamic link library is executed .
2) RTLD_NOW : Show in dlopen Resolve all undefined symbols before returning , Once unresolved ,dlopen Will return an error .
dlopen When the call fails , Will return NULL value , Otherwise, the operation handle is returned .
function dlsym : Take the function execution address
Archetype : void *dlsym(void *handle, char *symbol);
dlsym Handle according to DLL (handle) And symbols (symbol), Returns the execution code address of the function corresponding to the symbol . This address , You can execute the corresponding function with parameters .
Such as program code : void (*add)(int x,int y); /* Explain the dynamic function to be called add */
add=dlsym("xxx.so","add"); /* open xxx.so Shared library , take add Function address */
add(89,369); /* With two parameters 89 and 369 call add function */
function dlclose : Close DLL
Archetype : int dlclose (void *handle);
dlclose The DLL used to close the specified handle , Only if the usage count of this DLL is 0 when , Will be actually unloaded by the system .
4.2、 Load the instance of dynamic link library
In the following example, we will dynamically load libmymath.so Link library , To call add() and sub() Two functions .
/*main.c*/
#include <stdio.h>
#include <dlfcn.h>
int main(void)
{
void*dp=dlopen("libmymath.so",RTLD_LAZY);
if(NULL==dp)
{
printf(" Failed to open dynamic link library !");
return1;
}
// Define function pointers
int(*fn_add)(int,int)=NULL;
int(*fn_sub)(int,int)=NULL;
fn_add=dlsym(dp,"add");
fn_sub=dlsym(dp,"sub");
if(NULL==fn_add|| NULL==fn_sub)
{
printf(" Failed to find function in DLL !");
return1;
}
printf("1+ 2 = %d\n", fn_add(1, 2));
printf("1- 2 = %d\n", fn_sub(1, 2));
dlclose(dp);
return0;
}
take libmymath.so and main.c Put it in the same directory , Execute the following command :
gcc -rdynamic -s -o main.bin main.c -ldl
-rdynamic Option to specify that the output file is dynamically linked
-s Specify to delete the symbol table in the target file ,
-ldl Indicates the assembly procedure ld Need to load dl function library .
Last run main.bin The results are the same as above .
4.3、Windows Lower and Linux The following shows the comparison of loading dynamic link libraries
Windows Drop the dynamic link library to “.dll” For the suffix , and Linux The dynamic link library under is based on ”.so” It's a suffix .
The functionality | Windows Next | Linux Next |
Open and load dynamic link library | LoadLibrary | dlopen |
Get the function address in the dynamic link library | GetProcAddress | dlsym |
Close DLL | FreeLibrary | dlclose |
The header file that should be included when using | Winbase.h(include Windows.h) | dlfcn.h |
5、 A special case
Let's look back , It is found that when using static libraries and using dynamic libraries implicitly, it is used by the target program gcc The order is exactly the same , When a static library has the same name as a dynamic library ,gcc Which library file does the command use ? With the feeling that we must go to the end of the problem , Let's try . Delete first .c and .h All documents outside , Restore to the state of the program we just edited .
gcc -c add.c
gcc -c sub.c
ar crlibmymath.a sub.o add.o
gcc -shared -fPCI -olibmyhello.so sub.o add.o
Now the directory has two library files with the same name ( The dynamic library file has the same name as the static library file ):
libmymath.a 、 libmymath.so
Compile run program :
gcc -o main main.c -L. -lmymath
./main
./main: error while loading shared libraries:libmymath.so: cannot open shared object file: No such file or directory
Slave program ./main It's easy to know from the running results , When Linux Static libraries and Linux When the dynamic library has the same name , gcc The command takes precedence over the dynamic library . If you force the use of static libraries, you need to add -static Option support , namely :
gcc-static -o main main.c -L. -lmymath
The executable of linked static library is obviously larger than that of linked dynamic library .
6、 Look at the symbols in the library
1、 Use nm The command can print all symbols involved in stock out . Libraries can be either static or dynamic
Three common symbols :
① Called in the library , But not defined in the library ( Indicates the need for other libraries to support ), use U Express
② Functions defined in the library , use T Express
③“ Weak state ” Symbol , Although they are defined in the library, they may be overwritten by symbols with the same name in other libraries , use W Express .
2、 use ldd Command to view a shared library that an executable program depends on .
7、Linux Next so Export the specified function
Linux Compile below so Export the specified function in the source file :
1、 Add... At the beginning of the document :#defineDLL_PUBLIC __attribute__((visibility("default")))
2、 Add... Before the function to be exported in the file :extern "C" DLL_PUBLIC
3、Linux Next dynamic library (so) It does not export by default when compiling , stay Makefile Need to add :-fvisibility=hidden
边栏推荐
- Dragging El table sortablejs
- Open Oracle server under Linux to allow remote connection
- Which of the top ten securities companies has the lowest Commission and is the safest and most reliable? Do you know anything
- numpy.logical_and()
- Role of message queuing
- PHP encapsulates a file upload class (supports single file and multiple file uploads)
- 使用swiper左右轮播切换时,Swiper Animate的动画失效,怎么解决?
- 植物生长h5动画js特效
- MYSQL数据高级
- Mise en œuvre du rendu de liste et du rendu conditionnel pour l'apprentissage des applets Wechat.
猜你喜欢
微信小程序學習之 實現列錶渲染和條件渲染.
CVPR 2022 Oral | 英伟达提出自适应token的高效视觉Transformer网络A-ViT,不重要的token可以提前停止计算
Producer / consumer model
机器学习——主成分分析(PCA)
整理接口性能优化技巧,干掉慢代码
SVG+js拖拽滑块圆形进度条
How does home office manage the data center network infrastructure?
Floating point notation (summarized from cs61c and CMU CSAPP)
JS singleton mode
415 binary tree (144. preorder traversal of binary tree, 145. postorder traversal of binary tree, 94. inorder traversal of binary tree)
随机推荐
[input method] so far, there are so many Chinese character input methods!
416 binary tree (first, middle and last order traversal iteration method)
4. classification management business development
CVPR 2022 Oral | 英伟达提出自适应token的高效视觉Transformer网络A-ViT,不重要的token可以提前停止计算
读取csv(tsv)文件出错
tf.errors
如何在一个页面上使用多个KindEditor编辑器并将值传递到服务器端
3.员工的增删改查
Yolov6: the fast and accurate target detection framework is open source
How does home office manage the data center network infrastructure?
形状变化loader加载jsjs特效代码
leetCode-1823: 找出游戏的获胜者
Detailed explanation of PHP singleton mode
解决微信小程序rich-text富文本标签内部图片宽高自适应的方法
一群骷髅在飞canvas动画js特效
Internet of things? Come and see Arduino on the cloud
Using pandas to read SQL server data table
线程池的状态
leetCode-929: 独特的电子邮件地址
Machine learning perceptron and k-nearest neighbor