当前位置:网站首页>GCC compilation process and dynamic link library and static link library
GCC compilation process and dynamic link library and static link library
2022-07-03 11:31:00 【Ch_ champion】
1. The introduction of the 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). windows The above corresponds to .lib .dll linux The above corresponds to .a .so
Let me introduce you to Linux Under the gcc Several options for compiling
g++ -c hellospeak.cpp
Will hellospeak.cpp Options -c Used to tell the compiler to compile the source code without executing the link , The output is an object file . The default file name is the same as the source file name , Just change its suffix to .o. for example , The above command will compile the source file hellospeak.cpp And generate object files hellospeak.o;
The following command links the above two source files into a single executable program :
$ g++ hellospeak.cpp speak.cpp -o hellospeak
without -o And later parameters , The compiler uses the default a.out
In this case, we will generate hellospeak Such executable programs .
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 .
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
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.
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 .
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 .
Refer to :
http://www.cnblogs.com/skynet/p/3372855.html Saylor ( Very detailed ! It's worth looking at )
http://www.cnblogs.com/iloveyoucc/archive/2012/08/29/2661851.html
Reference source : You know Guo Wuxin
2. GCC The build process
2.1 GCC Definition
at present Linux The most commonly used C The language compiler is GCC ( GNU Compiler Collection ), It is GNU In the project ANSI C Standard compiler system , Can compile with C 、 C++ and Object C A program written in a language . GCC Not only is it very powerful , The structure is also extremely flexible . The most praiseworthy point is that it can support various languages through different front-end modules , Such as Java 、 Fortran 、 Pascal 、 Modula-3 and Ada etc. . to open up 、 Freedom and flexibility are Linux The charm of , And that's in GCC The embodiment of the above is that the programmer can better control the whole compilation process through it . In the use of GCC When compiling a program , The compilation process can be broken down into four phases :
Preprocessing ( Pre-Processing )
compile ( Compiling )
assembly ( Asse mbling )
link ( Linking )
Linux The programmer can let... According to his own needs GCC At the end of any stage of compilation , To check or use the compiler's output at this stage , Or control the final binary file , In order to prepare for future debugging by adding different numbers and types of debugging code . Like other compilers in common use , GCC It also provides flexible and powerful code optimization functions , It can be used to generate more efficient code .
GCC Provides 30 Multiple warning messages and three warning levels , Using them helps to enhance the stability and portability of the program . Besides , GCC And for the standard C and C++ Language has expanded a lot , Improve the efficiency of program execution , Help the compiler optimize the code , Can reduce the workload of programming .
2.2 GCC The build process
1)gcc Pretreatment stage : Mainly for the included header file (#include ) And macro definition (#define,#ifdef … ) To deal with . have access to “gcc -E” Give Way gcc Stop the compilation process after preprocessing , Generate *.i file .
gcc -E hello.c -o hello.i
2)gcc Compile phase :gcc First of all, check the normalization of the code , Whether there are grammar mistakes, etc . To determine what the code actually does , After checking to be correct ,gcc Translate the code into assembly language . Users can use -S Options to view , This option only goes to
Line compile without assembly , Generate assembly code .
gcc -S hello.i -o hello.s
3)gcc Assembly stage : Generate target code *.o ; There are two ways : Use gcc Generate target code directly from source code gcc -c *.s -o *.o And using assembler to generate object code from assembly code as *.s -o *.o
gcc -c hello.s -o hello.o
as hello.s -o hello.o
It can also be used directly as *.s, take Perform assembly 、 The linking process generates the executable a.out, It can be used as above -o Options Specify the format of the output file .
4)gcc Link phase : Generate executable files ; The executable formats that can be generated are : a.out/*/, Of course, there may be other formats .
gcc hello.o Generate executable files a.out
gcc hello.o -o hello Generate executable files hello
2.3 gcc Common compilation options :
2.3 gcc Use of linked library files
stay linux When developing software , It's rare not to use a third-party library at all , Generally speaking, we need the support of one or more function libraries to complete the corresponding functions . From a programmer's point of view , The function library is actually some header files ( .h ) And libraries ( .so perhaps .a ) Set . although Linux Most of the functions below default to Put the header file in /usr/include/ Under the table of contents , and Library files are placed in /usr/lib/ Under the table of contents , But that's not all the case . Because of this , GCC At compile time, you must have your own way to find the required header files and library files . GCC Search the directory to find the required files , -I Options can be directed to GCC Add a new directory to the header file search path . for example , If in /home/justin/include/ There are header files needed for compilation in the directory , In order to make GCC To be able to find them , You can use -I Options :
gcc foo.c -I /home/justin/include -o foo
Again , If you use a library file that is not in a standard location , So you can go through -L Option direction GCC Add a new directory to the search path of the library file . for example , If in /home/xiaowp/lib/ There are library files needed when there are links in the directory libfoo.so , In order to make GCC Can find it smoothly , You can use the following command :
gcc foo.c -L /home/justin/lib -lfoo -o foo
It's worth explaining -l Options , It indicates GCC To connect library files libfoo.so . Linux There is a convention when naming the following library files , That is to say, we should use lib Start with three letters , Because all library files follow the same specifications , So in use -l Option to specify the name of the linked library lib Three letters , in other words GCC In the face of -lfoo When processing , Will automatically go to the link named libfoo.so .
Linux The following library files are divided into two categories Dynamic link library ( Usually, the .so ending ) and Static link library ( Usually, the .a ending ), The difference between the two is that the code required for program execution is dynamically loaded at run time , Still loaded statically at compile time . By default ,GCC Dynamic link library is preferred when linking , Consider using static link libraries only if they don't exist , Add... At compile time if necessary -static Options , Force the use of static link libraries . for example , If in home/justin/lib/ There are library files needed when there are links in the directory libfoo.so and libfoo.a , In order to make GCC Only use static link library when linking , You can use the following command :
gcc foo.c -L /home/justin/lib -static -lfoo -o foo
For dynamic library and static library file creation method , See the introduction of the above library .
Refer to :
GCC compile c Program method and process analysis
linux Next use GCC compiler 、 Simple generation of static library and dynamic library
边栏推荐
- 浅析-JMM内存模型
- Illustrated network: what is virtual router redundancy protocol VRRP?
- Using activity to realize a simple inputable dialog box
- BI技巧丨权限轴
- (2) Base
- Stm32hal library upgrades firmware based on flash analog U disk (detailed explanation)
- FL Studio 20 unlimited trial fruit arranger Download
- 2022-07-02: what is the output of the following go language code? A: Compilation error; B:Panic; C:NaN。 package main import “fmt“ func mai
- C language log base zlog basic use
- Abandon the Internet after 00: don't want to enter a big factory after graduation, but go to the most fashionable Web3
猜你喜欢
Arctangent entropy: the latest SCI paper in July 2022
用了这么久线程池,你真的知道如何合理配置线程数吗?
LeetCode 46:全排列
DS90UB949
聊聊Flink框架中的状态管理机制
2022 东北四省赛 VP记录/补题
Incremental database backup - DB incr DB full
Driver development based on I2C protocol
Résumé des questions d'entrevue (2) Modèle io, ensemble, principe NiO, pénétration du cache, avalanche de rupture
Understand go language context in one article
随机推荐
Summary of interview questions (2) IO model, set, NiO principle, cache penetration, breakdown avalanche
AMS series - application startup process
Tablespace creation management and control file management
Numpy np.max和np.maximum实现relu函数
表空间创建管理及控制文件管理
P3250 [HNOI2016] 网络 + [NECPC2022] F.Tree Path 树剖+线段树维护堆
Leetcode 46: full arrangement
C language AES encryption and decryption
FL Studio 20 unlimited trial fruit arranger Download
Project management essence reading notes (VII)
ASP. Net hotel management system
Touch and screen automatic rotation debugging
Application of high-precision indoor positioning technology in safety management of smart factory
AOSP ~ NTP ( 网络时间协议 )
Key switch: press FN when pressing F1-F12
Ext file system mechanism principle
Kotlin's use of the no Arg compiler plug-in in gradle
Struct function & function pointer
Analysis of EPS electric steering system
JGG专刊征稿:时空组学