[C ++] - Linux gcc compiler, static library, dynamic library

gcc compilation process

Pretreatment -> (* .i) compile -> (* .s assembly files) compilation -> (* .o binary machine code) Links -> executable file

  1. Pretreatment: preprocessor corresponding source files macro expansion gcc -E test.c -o test.i
  2. Compile: gcc compiler to compile the c file files gcc -S test.i -o test.s
  3. Assembly: use as command (assembler) files will be compiled into machine code compilation (binary) as test.s -o test.o
  4. Link: object files with external symbolic link to obtain an executable binary gcc test.o -o test

The difference between static and dynamic libraries

windows: static library (* .lib) dynamic libraries (* .dll)
Linux: static library (* .a) dynamic libraries (* .so)

Dynamic link libraries are only used when the implementation is not directly compiled into an executable file, and a dynamic library can be multiple
use program, it can be called a shared library
static library will be integrated into the program, not during program execution load static library.
Therefore, static library will make your program bloated and difficult to upgrade, but relatively easy to deploy. The DLL will make your program light
will be easy to upgrade but difficult to deploy

If at compile time, a program link static library, the linker searches for the library and copying directly into the executable file (conducive to the deployment, but too bloated); for dynamic libraries, at compile time and not be linked to the code , but it will be loaded at runtime (not conducive to the deployment, but the program light)

Create a static library

gcc -c add.c 
ar crsv libadd.a add.o
gcc -o add.exe testadd.c -ladd -L.//-L.为设置为当前路径,也可直接将.a文件复制到 /usr/local/lib目录下)

Creating a dynamic library

gcc -fPIC -Wall -c add.c
gcc -shared -o libadd.so add.o
sudo cp libadd.so /usr/local/lib  //当做好动态库后,要把动态库移到 /usr/local/lib,再执行以下命令
sudo ldconfig   //该命令会更新/etc/ld.so.cache的内容,将新加入的库路径写入其中,这样,可执行程序就可以在执行时找到动态库
gcc -o add.exe testadd.c -ladd
Published 43 original articles · won praise 4 · Views 1192

Guess you like

Origin blog.csdn.net/weixin_42176221/article/details/105203735