[Linux C] Static Libraries, Dynamic Shared Libraries and Loadable Libraries in Linux

Reprinted from: https://blog.csdn.net/imxiangzi/article/details/45871949/

Linux library classification

There are currently two Linux C/C++ libraries that can be created:

  • Static library (.a): will be linked into the object code and become part of the application.

  • Dynamic Shared Link Library (.so): This library has only one structure, but can be used in two ways.

    • I. Dynamic linking at runtime but static dependencies. These libraries need to exist during the compilation/linking phase. Shared libraries will not be included in the executable file, but need to be bound at runtime.

    • II. Use dynamic loading and linking system functions for dynamic loading/unloading and linking during execution (eg browser plugins).

library naming convention

Libraries are usually prefixed with 'lib', which applies to all C standard libraries. When linking, referencing the library on the command line will not require a prefix or suffix to include the library.
Consider the following link command:

gcc src-file.c -lm -lpthread

In this example, the math library and thread library are required for linking, and they are stored in /usr/lib/libm.a and /usr/lib/libpthread.a.

static library

How to create a library (object code archive):

  • compile
gcc -Wall -c calc_*.c       //编译成*.o中间文件
  • Create static library
ar -cvq libcalc.a calc_*.o  //打包生成*.a静态库文件
  • List files in static library
ar -t libcalc.a
  • link library
gcc -o calc calc.c libcalc.a                        //链接同目录/系统目录下的静态库
gcc -o calc calc.c libcalc.a  -L/path/to/lib -lcalc //链接其他目录的静态库

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730955&siteId=291194637