Create and use static/dynamic libraries in unix/linux environments __linux

Source: Internet
Author: User
the role of the library

In general, there are two reasons for the existence of the library, one is the reuse of code, the other is the separation of declaration and implementation. The use of similar functions to encapsulate the module into a library, so that the reuse of code, management and distribution become a lot simpler, such as the famous open source graphics library ncurses, you can compile, you can directly use the already compiled ready-made library files. In addition, because the library is a binary file, in a sense, the implementation part of the feature is hidden, which provides a way for the protection of business code.
The library file can be divided into dynamic and static libraries by link and timing, and the following are the ways to create and use them in a Linux environment. Static link library

A static library is the link phase of a program in which the code used is directly linked to the library in the executable file. A statically linked executable contains all the library functions it needs: all library functions are connected to the program. Such programs are complete and run without the support of external libraries. One of the advantages of static linking programs is that they do not need to do environmental preparation before they are installed.
In Linux, the extension of a static library is usually. A, it is just some object file (. o) of the Archive (archive) or packaging, in addition, in order to link to quickly locate the symbols (functions, variable names, etc.), the static library will also contain a symbol of the index.
The process of creating a static library is simple, with only two AR and ranlib commands to use in addition to the tools necessary to compile it. AR can archive each target file and ranlib the AR-generated archive (that is, the static library file). Let's say there are several source files: plus.c, SUB.C and corresponding header files, and a main file main.c to call functions in the library file, respectively:
PLUS.C,

1
2
3
4
5
6
#include "plus.h"
int
plus (int a, int b)
{return
    a + b;
}

SUB.C,

1
2
3
4
5
6
#include "sub.h"
int
sub (int a, int b)
{return
    a-b;
}

MAIN.C,

1
2
3 4 5 6 7 8 9
Ten
11
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "plus.h"
int
Main (int argc, char **argv)
{
    int a = Plus (1, 2);
    printf ("%d/n", a);
    return 0;
}

The following PLUS.C and SUB.C compiled, made into a static library libmath.a, followed by:

1
2
3
$ cc-c plus.c sub.c
$ ar rc libmath.a plus.o sub.o
$ ranlib libmath.a

Now our libmath.a Static library has been made, which uses the two options of the AR command, c means that if the library file does not exist, it is created, and R indicates that if a target file already exists in the library file and is older, the substitution is performed. Using this static library is simpler:

1
2
3
$ cc main.c-l.-lmath-o main
$/main
3
Dynamic Link library

Dynamic libraries are similar to static libraries and are collections of individual target files. But compared to statically linked programs, dynamic link executable programs are much smaller: These programs run with the support of external shared libraries, and therefore do not seem to be complete. In addition to the small program body, dynamic linking allows a package to specify the necessary libraries without having to mount the library into the package. Dynamic Link technology also allows multiple running programs to share a library so that there is no more than one copy of the same code sharing memory. For these reasons, most current applications use dynamic link technology.
The extension in Linux is usually. So. When linked, however, it is not linked to an executable file, but is dynamically loaded into memory at execution time (as needed) by the dynamic loading module of the operating system and linked to the appropriate location in the executable address space.
The creation of a dynamic-link library is also divided into two phases: compile and archive, but the difference is that you need to use a few different command options in both phases. First, you need to compile the source file into a target file that becomes a positional-independent code (pic:position independent code) that can be added to any location in memory without the need for the loader to reposition it, referring to the linker and loader and the The programmer's self-cultivation-a more detailed description of link loading and library. Next you need to "archive" These location-independent codes as. so files. The whole process is just a tool, gcc. or the source file above, execute the following command:

1
2
$ cc-c-fpic plus.c SUB.C $ cc-shared-o libmath.so *.o

In this way, the dynamic library file containing PLUS.O and SUB.O is created libmath.so. Where the-fpic or-fpic option of the CC (GCC symbolic Link) command creates a location-independent target file, you can use the-shared option to create the final dynamic library file.
There are two ways to use dynamic library files, one of which is to have the dynamic loading module of the operating system (such as ld-linux.so.2) load the runtime at execution time. The other is to use the DL library to dynamically load library files in your code.
Introduce the first method first. Using this method requires that you specify the library name and its path (for the dynamic library you write) when you compile the executable file:

1
$ cc main.c-l.-lmath-o Main

The executable file main is created, and the above command does not link the corresponding target code in libmath.so to main (you can compare the size of main and static links here), just find and confirm the symbols used in MAIN.C in the library. But usually this main is still unable to perform normally, this involves the system to find the path of the dynamic library, the system is usually only in some specified directory (standard path) to find the required library files, if the standard path can not find the required library, then the environment variable Ld_library_ PATH, if present, finds under the directory specified, and if it is still not found, the error occurs. Because the libmath.so is in the current directory of main, the current directory is usually not in the standard path column. To enable libmath.so to be found and loaded, you can put it in a standard path, but a better way is to add its directory to the Ld_library_path variable. Execute the following command:

1
2
3
4
$ ld_library_path= $LD _library_path:. # Add current directory
$ export Ld_library_path # Export environment variables so that they are available in the child shell
$/main
3

  
The following is an introduction to using the DL library to load dynamic libraries, where functions in the DL library are rarely concise, see MAIN.C Code:

1
2
3
4
5
6
7 8 9 of
21
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <dlfcn.h >
#include "plus.h"
int
main (int argc, char **argv)
{
    void * Lib_handle = Dlopen ("./ Libmath.so ", rtld_lazy);
    if (Lib_handle)
    {
        int (*plus_ptr) (int, int) = Dlsym (Lib_handle, "plus");
        if (plus_ptr)
        {
            int a = PLUS_PTR (1, 2);
            printf ("%d/n", a);
        }
        Dlclose (Lib_handle);
    }
    return 0;
}

In Main.c, you first use Dlopen to open the dynamic library that you want, where the parameter rtld_lazy indicates that the load will be loaded only if you need to call the library. Dlopen returns a handle, Dlsym uses the handle and symbol to obtain the address of the corresponding function, where the int (*) (int) function pointer is used to receive the plus function's address. Then use the resulting function pointer to call the corresponding function, and finally close the handle with the Dlclose function. Compiling this program requires the use of the DL dynamic link library, so you need to use the GCC-ldl option:

1
2
3
$ cc Main.c-ldl-o main
$/main
3
. So and. A file comparison

Finally, attach the contents of the LIBMATH.A and libmath.so files and view them using the Objdump-D option:
LIBMATH.A,

In archive libmath.a:

plus.o:     file format elf32-i386
disassembly the section. Text:
00000000 <plus ":
   0:"                   	push   %ebp
   1:	e5                	mov    %esp,%ebp
   3:	8b 0c             	mov    0xc (%EBP),%eax
   6:	8b    0x8 (%EBP),%edx
   9:	8d    of Lea (%edx, %eax,1),%eax
   C:	5d                   	pop    %ebp
   d:	c3                   	ret    

sub.o:     file Format elf32-i386
disassembly of section. Text:
00000000 <sub>:
   0:                   	push   %ebp
   1:	89 e5                	mov    %esp,%ebp
   3:	8b 0c             	mov    0xc (%EBP),%eax
   6:8b/             	mov    0x8 (%EBP),%edx
   9:	d1                	mov    %edx,%ecx
   B:	C1                	Sub    %eax,%ecx
   D:	C8                	mov    %ecx,%eax
   f:	5d                   	Pop    %ebp
  :	c3                   	ret

Libmath.so:

Libmath.so:file format elf32-i386 disassembly of section. init:00000324 <_init>: 324:55 p             	Ush%ebp 325:89 e5 mov%esp,%ebp 327:53 push%ebx 328:83 EC 04
Sub $0x4,%esp ...              	0000044c <plus&gt: 44c:55 push%ebp 44d:89 e5 mov%esp,%ebp 44f:8b 0c mov 0xc (%EBP),%eax 452:8b mov 0x8 (%EBP),%edx 455:8d-Lea (
 %edx,%eax,1),%eax 458:5d pop%ebp 459:C3 ret 45a:90                	45b:90 NOP 0000045c <sub&gt: 45c:55 push%ebp 45d:89 e5 mov%esp,%ebp 45f:8b 0c mov 0xc (%EBP),%eax 462:8b mov 0x8 (%EBP),%edx 465   : D1 mov%edx,%ecx 467:29 C1 sub%eax,%ecx 469:89 C8 mov %ecx,%eax 46b:5d pop%ebp 46c:c3 ret 46d:90 NOP

0 NOP 46f:90 NOP ...                	Disassembly. Fini:000004a8 <_fini&gt: 4a8:55 push%ebp 4a9:89 e5 mov%esp,%ebp 4ab:53 push%ebx 4ac:83 EC Sub $0x4,%esp 4af:e8 00 00 00 0 0 call 4b4 <_fini+0xc> 4b4:5b pop%ebx 4b5:81 C3 1b Add $0x1b40,%                   	EBX 4bb:e8 d0 FE FF FF call 390 <__do_global_dtors_aux> 4c0:59 pop%ecx 4c1:5b
 Pop%ebx 4c2:c9 leave 4C3:C3 ret

Visible, relative. A,.so has a lot of extra code snippets, where it's more important to <_init> and <_fini> segments. They do some upfront and post-processing work, such as <_init> typically perform some of the initialization work in the. So library (c + + may be a global or static object constructor), for example, before Dlopen returns.

http://www.dutor.net/index.php/2010/07/dynamic-static-library/

Original part

----------------------------------------------------------

Link. A static library, if it is compiled with Makefile, invoke the method:

Add am_cflags parameter: am_cflags =-dts_pointercal=/"@TS_POINTERCAL @/" $ (debugflags)-l$ (top_srcdir)/src/-ljpeg

(. A library location is "$ (top_srcdir)/src/")

Add header file: INCLUDES =-i$ (top_srcdir)/src

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.