Create a static library in Linux. A and dynamic libraries. So

Source: Internet
Author: User
Tags naming convention

Transferred from: http://www.cnblogs.com/laojie4321/archive/2012/03/28/2421056.html

Create a static library in Linux. A and dynamic libraries. So

We usually make some common functions into libraries for other programs to use.

function library is divided into static library and dynamic library two kinds.

1. Static function library

The name of such a library is generally libxxx.a; the file compiled from the static function library is larger, because all the data of the entire library is integrated into the target code, and his advantages are obvious, that is, the compiled execution program does not require external library support, because all the functions used are already compiled. This, of course, will also be a disadvantage, because if the static library changes, then your program must be recompiled.

2. Dynamic Function Library

The name of such a library is generally libxxx.so; relative to the static function library, the dynamic function library is not compiled into the target code when it is compiled, and your program executes to the relevant function to invoke the corresponding function in the library, so the dynamic function library produces the smaller executable file. Since the library is not integrated into your program, it is applied and invoked dynamically while the program is running, so you must provide the appropriate library in the running environment of the program. The change of dynamic function library does not affect your program, so the upgrade of dynamic function library is more convenient.
The Linux system has several important directories for storing the appropriate libraries, such as/lib/usr/lib

The static library is connected to the target code when the program is compiled, and the static library is no longer needed when the program runs .

Dynamic libraries are not connected to the target code when the program is compiled, but are loaded only when the program is running, so dynamic inventory is also required when the program is running .

This article focuses on how to create static and dynamic libraries in Linux and use them as an example.

Before creating a function library, let's prepare an example source program and compile the source program of the library into an. o file.

The 1th step: The program--hello.h, HELLO.C and main.c are given examples;

Hello.h (see program 1) is the header file for the function library.

HELLO.C (see program 2) is the source of the function library, which contains the public function hello, which will output "Hello xxx!" on the screen.

MAIN.C (see program 3) is the main program for the test library file, and the public function Hello is called in the main program.

Program 1:hello.h

#ifndef Hello_h
#define Hello_h

void Hello (const char *name);

#endif//hello_h

Program 2:HELLO.C


#include <stdio.h>

void Hello (const char *name)
{
printf ("Hello%s!\n", name);
}


Program 3:MAIN.C
#include "hello.h"

int main ()
{
Hello ("everyone");
return 0;
}

2nd step: Compile the hello.c into an. o file;

Whether a static library or a dynamic library, it is created by an. o file. Therefore, we must first compile the source program hello.c through GCC into an. o file.

At the system prompt, type the following command to get the hello.o file.

# gcc-c HELLO.C

#

(Note 1: This article does not describe the use of commands and their parameters, if you want to learn more about them, refer to other documents.) )

(Note 2: The first character "#" is the system prompt, you do not need to type, the following is the same.) )

We run the LS command to see if the hello.o file survived.

# ls

HELLO.C hello.h hello.o main.c

#

(Note 3: The first character is not "#" to run the results for the system, same as below.) )

In the results of the LS command, we see the hello.o file, which is done in this step.

Let's start by looking at how to create a static library and use it.

3rd step: Create a static library from the. o file;

The naming convention for Static library filenames is prefixed with lib, followed by a static library name with a. a extension. For example: We will create a static library named Myhello, then the static library file name is LIBMYHELLO.A. You need to be aware of this when creating and using static libraries. Create a static library with the AR command.

At the system prompt, type the following command to create a static library file, Libmyhello.a.

# ar CR libmyhello.a hello.o

#

We also run the LS command to see the results:

# ls

hello.c hello.h hello.o libmyhello.a main.c

#

There are libmyhello.a in the results of the LS command.

4th step: Use the static library in the program;

The static library is finished, how to use its internal function? You only need to include a prototype declaration of these common functions in the source program that uses these common functions, and then specify the static library name when you generate the target file with the GCC command, and GCC will connect the public function to the destination file from the static library. Notice that GCC adds the prefix lib to the static library name and then appends the extension. A to the static library file name to find the static library files.

In program 3:MAIN.C, we include the header file hello.h of the static library, and then call the public function hello directly in main program main. The following Mr. into the target program Hello, then run the Hello program to see how the results.

# gcc-o Hello main.c-l.-lmyhello

#./hello

Hello everyone!

#

Let's delete the static library file and try the common function hello whether it is really connected to the target file hello.

# RM LIBMYHELLO.A

Rm:remove regular file ' libmyhello.a '? Y

#./hello

Hello everyone!

#

The program runs as usual, and the public functions in the static library are already connected to the target file.

Let's continue to look at how to create a dynamic library in Linux. Let's start with the. o file.

5th step: Create a dynamic library file from an. o file;

The dynamic library file name specification is similar to the static library file name naming specification and also adds the prefix lib to the dynamic library name, but its file name extension is. So. For example: We will create a dynamic library named Myhello, then the dynamic library file name is libmyhello.so. Use GCC to create a dynamic library.

At the system prompt, type the following command to get the dynamic library file libmyhello.so.

# Gcc-shared-fpci-o libmyhello.so hello.o

#

We still use the LS command to see if the dynamic library file is generated. the "PIC" command-line tag tells GCC that the generated code does not include a reference to the specific memory location of the function and variable, because it is not yet known which memory address space the application using the message code will connect to. The compiled hello.o can be used to create a shared link library. To create a shared link library, you only need to use GCC's "-shared" tag .

# ls

hello.c hello.h hello.o libmyhello.so main.c

#

The 6th step: Use the dynamic library in the program;

Using a dynamic library in a program is exactly the same as using a static library, and it is also a prototype declaration that includes these common functions in the source program that uses these common functions, and then indicates that the dynamic library name is compiled when the target file is generated with the GCC command. We run the GCC command first to generate the target file, and then run it to see the results.

# gcc-o Hello main.c-l.-lmyhello

#./hello

./hello:error while loading shared libraries:libmyhello.so:cannot open Shared object file:no such file or directory

#

Oh! Something went wrong. Quick look at the error prompt, the original is not found dynamic library file libmyhello.so. At run time, the program looks for the required dynamic library files in directories such as/usr/lib and/lib. If found, loads the dynamic library, otherwise it will prompt similar errors to terminate the program. We'll copy the file libmyhello.so to the directory/usr/lib and try again.

(Use the "-lmyhello" flag to tell the GCC driver to reference the shared function library libmyhello.so during the connection phase.) "-L." The tag tells the GCC library that it might be in the current directory. Otherwise the GNU Connector looks for the standard system function directory: It searches for the Dt_rpath segment of the 1.elf file-2. Environment variable Ld_library_path-3./etc/ld.so.cache file list -4./lib/,/usr/ The Lib directory finds the library file and loads it into memory, but the shared library we generate is not added to any of the 4 paths listed above in the current folder, so an error occurs after execution)

# MV Libmyhello.so/usr/lib

#./hello

Hello everyone!

#

It worked. This further illustrates that a dynamic library is required when the program is running.

Also: Since the connector will search for the directory specified by Ld_library_path, we can set the environment variable to the current directory:

Execute First:

Export ld_library_path=$ (PWD)

Re-execution:

./hello

Success!

finally : execution:

Ldconfig/usr/zhsoft/lib

Note: When a user creates or copies a dynamic link library under a directory, you can execute the "ldconfig directory Name" command if you want it to be shared by the system. The function of this command is to let Ldconfig share the dynamic-link library under the specified directory with the system, meaning: in the cache file/etc/ The shared library in the specified directory is appended to the Ld.so.cache. This example lets the system share the dynamic link library under the/usr/zhsoft/lib directory. The command rebuilds the/etc/ld.so.cache file

Success!

You can view the process of invoking a dynamic library when the program executes:

# LDD Hello
Execute test and you can see how it calls functions in the dynamic library.
[Email protected] 20090505]$ LDD Hello
Linux-gate.so.1 = (0x00110000)
libmyhello.so =/usr/lib/libmyhello.so (0x00111000)
libc.so.6 =/lib/libc.so.6 (0x00859000)
/lib/ld-linux.so.2 (0x0083a000)

We looked back and found that using a static library and using a dynamic library to compile the GCC commands used by the target program is exactly the same as when the static library and the dynamic library have the same name, which library file does the GCC command use? Hold on to the problem will be to the end of the mood, to try.

Remove all files except. C and. h and revert to the state of the example program we just finished editing.

# rm-f Hello hello.o/usr/lib/libmyhello.so

# ls

HELLO.C hello.h MAIN.C

#

In order to create a static library file libmyhello.a and a dynamic library file libmyhello.so.

# gcc-c HELLO.C

# ar CR libmyhello.a hello.o

# Gcc-shared-fpci-o libmyhello.so hello.o

# ls

hello.c hello.h hello.o libmyhello.a libmyhello.so main.c

#

With the last ls command above, you can find that both the static library file libmyhello.a and the dynamic library file libmyhello.so have been generated and are in the current directory. We then run the GCC command to use the function library Myhello to generate the target file Hello and run the program hello.

# gcc-o Hello main.c-l.-lmyhello

#./hello

./hello:error while loading shared libraries:libmyhello.so:cannot open Shared object file:no such file or directory

#

It is easy to know from the results of the program Hello run that when the static library and the dynamic library have the same name, the GCC command takes precedence over the dynamic library.

Note:

Compile parameter resolution


The main thing is an option for the GCC command line:
-shared This option specifies to generate a dynamic connection library (let the connector generate the export symbol table of type T, and sometimes the export symbol of the weakly connected W type) without which the external program cannot connect. Equivalent to an executable file
-fpic: represents compiled to a location-independent code, without this option, the compiled code is location-dependent, so dynamic loading is a way of copying code to meet the needs of different processes, but not to achieve the purpose of real code segment sharing.
-L.: Indicates the library to be connected in the current directory
-ltest: The compiler has an implicit naming convention when looking for dynamic connection libraries, which is to precede the given name with Lib, followed by. So to determine the name of the library
Ld_library_path: This environment variable indicates that the dynamic connector can load the path of the dynamic library.
Of course, if you have root permissions, you can modify the/etc/ld.so.conf file, and then call/sbin/ldconfig to achieve the same purpose, but if there is no root permission, then only the output Ld_library_path method.

Call the dynamic library when there are several problems often encountered, and sometimes, clearly has the library's header file in the directory through the "-I" include, the library is located in the file through the "-l" parameter boot, and specified the "-L" library name, but through the LDD command to see, it is dead and alive can not find your designated link , you have to specify the directory of the dynamic library by modifying the Ld_library_path or/etc/ld.so.conf file. This is usually done to solve the problem where the library cannot be linked.

Search path order when static library links:

1. LD will go to the parameters in the GCC command-l

2. Re-search for GCC environment variables Library_path

3. Find the default directory/lib/usr/lib/usr/local/lib This is the original compile GCC when written in the program

Dynamic Link-time, execution-time search path order:


1. The dynamic library search path specified when compiling the target code;

2. Environment variable LD_LIBRARY_PATH the specified dynamic library search path;

3. The dynamic library search path specified in the configuration file/etc/ld.so.conf;

4. The default dynamic library search path/lib;

5. The default dynamic library search path/usr/lib.

About environment variables:

Library_path environment variable: Specifies the program static link library file search path

LD_LIBRARY_PATH environment variable: Specifies the program dynamic link library file search path

Note:

As a Linux program developer, it is best to have a preliminary understanding of the location of development tools and resources. The following is a brief introduction to the main folders and applications.

1. Application (applications)

The application usually has a fixed folder, the system general program is placed in the/usr/bin, and later the system administrator installs the program in the local computer is usually placed under the/usr/local/bin or/opt folder. In addition to the system programs, most of the personal applications are placed under/usr/local, so it is important to keep the/usr clean. When upgrading or reloading the system, just back up the/usr/local program.

Some other programs have their own specific folders, such as the X Window System, usually installed in/usr/x11, or/USR/X11R6. The GNU compiler, GCC, is typically placed in/usr/bin or/usr/local/bin, and different Linux versions may have slightly different locations.

2. header file (head files)

In C and other languages, header files declare system functions and library functions, and some constants are defined. For the C language, the header file is basically scattered in/usr/include and its sub-folders. Other programming language library functions are distributed in compiler-defined places, such as in some Linux versions, where the X Window System library functions are distributed in/USR/INCLUDE/X11,GNU C + + library functions in/usr/include/g++. The location of these system library functions is a "standard location" for the compiler, where the compiler can automatically search for these locations.

If you want to refer to a header file that is located outside of the standard location, we need to add the-I flag when invoking the compiler to explicitly describe the folder where the header file is located. Like what

$ gcc-i/usr/openwin/include hello.c

will tell the compiler in addition to the standard location, but also go to/usr/openwin/include to see if there is a required header file. See the compiler's User manual (man gcc) for more information.

Library functions (Libraries Files)

Library functions are warehouses of functions, which are compiled and reused well. Typically, library functions work with each other to accomplish a specific task. such as the library functions that manipulate the screen (Cursers and Ncursers library functions), the database reads library functions (dbm Library functions), and so on.

Standard library functions that are called by the system are generally located in/lib and/usr/lib. The C compiler (the exact point of the connector) needs to know the location of the library function. By default, it searches only the standard C library functions.

The library function file usually starts with the letter lib. The following section identifies the purpose of the library function (for example, C library function with the C tag, the Math library function is marked with m), and the suffix after the decimal point indicates the type of library function:

. A refers to the static link library. So refers to the dynamic link library

To/usr/lib look, you will find that the library functions have both dynamic and static two versions.

As with header files, library functions are usually placed in a standard location, but we can also add new Search Folders with the-l identifier,-l specifies a specific library function file. Like what

$ gcc-o X11fred-l/usr/openwin/lib x11fred.c-lx11

The above command will be compiled with a link to the LIBX11 function library under the/usr/openwin/lib folder, compiled to generate x11fred.

Static link library (static Libraries)

The simplest library of functions is a simple set of functions. When you call a function in a library function, you need to include a header file that defines the library function in the calling function. We use the-l option to add a library of functions outside the standard library of functions.

Create a static library in Linux. A and dynamic libraries. So

Related Article

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.