"Go" Linux under GCC Build and use static library and dynamic library detailed

Source: Internet
Author: User
Tags naming convention

I. Basic CONCEPTS 1.1 what is a library

Libraries exist in a large number of Windows platforms and Linux platforms.

In essence, a library is a binary form of executable code that can be loaded into memory by the operating system.

Because of the different platforms of Windows and Linux (mainly compilers, assemblers, and connectors), the binary of the libraries is incompatible.

This article is limited to introducing libraries under Linux.

1.2 Types of libraries

There are two types of libraries under Li Nux: static libraries and shared libraries (dynamic libraries).

The difference between the two is that the code is loaded in a different time.

The code for the static library has been loaded into the executable program during compilation, so the volume is large .

the code for a shared library is loaded into memory when the executable is running, only a simple reference during compilation, so the code is small .

1.3 Significance of the existence of libraries

The library is written by someone else's existing, mature, reusable code that you can use, but remember to abide by the license agreement.

In reality, every program has to be a lot of basic underlying library, it is impossible for everyone's code to start from scratch, so the existence of the library is very unusual.

The benefit of a shared library is that if different applications call the same library, then only one instance of the shared library is needed in memory.

1.4 How library files are generated under Linux

The suffix of the static library is . A, which is produced in two steps

1. Build a heap from the source file compilation. O, each. o contains the symbol table for this compilation unit

The 2.ar command converts a lot of. O into. A as a static library

The suffix of the dynamic library is .so, which is generated by the GCC plus specific parameter compilation.

See the following example for specific methods.

1.5 How the library file is named, there is no specification

Under Linux, library files are generally placed under /usr/lib and /lib ,

The name of the static library is generally libxxxx.a, where xxxx is the name of the Lib

The name of the dynamic library is generally libxxxx.so.major.minor,xxxx is the name of the Lib, major is the major version number, minor is the sub-version number

1.6 How to know which libraries an executable program depends on

The ldd command can view a shared library that is dependent on an executable program.

For example:

Ldd/bin/lnlibc.so. 6=/lib/libc.so. 6 (0x40021000)/lib/ld-linux.so. 2 =/lib/ld-linux.so. 2 (0x40000000

You can see that the LN command relies on the LIBC library and the Ld-linux library.

1.7 How to locate a shared library file when executing the executable program

When the system loads executable code, it can know the name of the library it depends on, but it also needs to know the absolute path.

At this point, you need the system dynamic loader (Linker/loader)

The executable program for the ELF format is done by ld-linux.so* , which searches the Dt_prath segment of the elf file-the environment variable ld_library_path--/etc/ Ld.so.cache cache file List--/lib/,/usr/lib directory, locate the library file and load it into memory . Such as:

Export ld_library_path='pwd'

Add the current file directory as a shared directory

1.8 How to enable the system to find it after installing a new library

If installed under/lib or/usr/lib, then LD can be found by default, no additional action is required.

If you are installing in a different directory, you need to add it to the/etc/ld.so.cache file by following these steps:

1.VI Edit the /etc/ld.so.conf file, add the path to the directory where the library files are located

2. Run ldconfig-v and the command rebuilds the/etc/ld.so.cache cache file

Note :

1) The purpose of the Ldconfig command is to search for a shareable dynamic-link library (in the form of lib*.so*) in the default search directory/lib and/usr/lib and in the directory listed in the dynamic library configuration file/etc/ld.so.conf. This creates the connection and cache files required by the dynamic loader (ld.so) . The cache file defaults to/etc/ld.so.cache. Ldconfig typically runs at system startup, and when a user installs a new dynamic-link library, they need to run the command manually.

2)/etc/ld.so.cache contains all the link libraries found in the directory specified in/etc/ld.so.conf, stored sequentially .

Ii. examples of using GCC to generate static libraries and dynamic link libraries

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

The library is linked 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 when the program is run, so a dynamic library exists when the program is run.

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

For the sake of elaboration, we will do some preparatory work first.

2.1 Prepare the test code.

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.

Three programs are placed in the folder ~/testso

Program 1:hello.h

#define Hello_h     void Hello (constChar *#endif

Program 2:HELLO.C

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

Program 3:MAIN.C

#include  "hello.h"int  main ()  {      Hello ("  Everyone");       return 0 ;  }
2.2 The question is raised

Note : This time, our compiled hello.o is not compiled by Gcc-o (generate executable program), this is very simple, hello.c is a no main function. C program, so does not constitute a complete program, if using gcc- o Compile and connect it, GCC will error.

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.

This time, we have three kinds of ideas:

1) directly synthesize the target code into an. o file by compiling multiple source files .

2) by creating a static link library libmyhello.a, you can invoke the static link library when the main function calls the Hello function .

3) You can call the static link library when the main function calls the Hello function by creating the dynamic link library libmyhello.so .

2.3 Idea One: compiling multiple source files

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

gcc  -C  hello.c

Why not use Gcc-o Hello hello.c that's what we've said before, what do you mean by using-c? This involves common sense in GCC compilation options.

Gcc-o is to compile the. C source file into an executable binary code (the-o option is actually specifying the output file name, if the-C option is not added, GCC compiles the connection generation executable by default, the name of the file is specified by the-o option ), which includes the call as part of the GCC-- The real C compiler (CCL), and the external GNU Assembler (as) and connector tools (LD) that invoke the actual executable code in the output of the GNU C compiler.

Gcc-c is the end when the source file is converted to the target code using the GNU assembler, in which case only the C compiler (CCL) and assembler (as) are called, and the connector (LD) is not executed . So the target file of the output will not contain information that is necessary to be loaded and executed as a Linux program, but it can be connected to a program later.

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

ls hello.c hello.h hello.o main.c

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

Similarly compiled main

gcc  -C MAIN.C

Link two files to an. o file.

gcc  HELLO.O  MAIN.O-  o-  Hello

Run

$./Hellohello everyone!

Complete!

2.4 Idea two: Static link library

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

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  RCS  LIBMYHELLO.A  hello.o

We also run the LS command to see the results:

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

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

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 when you build the executable with the GCC command, and GCC will connect the public functions to the executable 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, so when we write the libraries that need to be connected, we write only the names, such as the LIBMYHELLO.A Library, write only: Myhello.

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  -static  -L.  -lmyhello$  . /Hellohello 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$  . /Hellohello Eceryone!

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

A disadvantage of a static link library is that if you run many programs at the same time, and they use the same library function, the same library function is copied in memory in large numbers. In this way, a lot of precious memory and storage space will be wasted. Linux with a shared link library can avoid this problem.

when a program uses a shared function library, it does not connect the function code in the connection phase, but only a reference to the link function. When the final function import memory begins to actually execute, the function reference is parsed and the code of the shared function library is actually imported into memory. In this way, the functions of the shared link library can be shared by many programs at the same time, and can be stored only once. Another advantage of sharing a library is that it can be updated independently, with no effect on the function that calls it .

2.5 idea three: Dynamic link library (Shared function library)

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

The dynamic library file name specification is similar to the static library filename 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. To create a dynamic library with GCC:

1) First step: Generate the hello.o target file, using the following command. Here you need to add the-fpic parameter, which is used to generate location-independent code for use in generating dynamic libraries:

gcc  -C-  o  hello.o  -fpic  hello.c

2) Step two: Use the-shared parameter to generate a dynamic library:

gcc  -shared-  o  libmyhello.so  hello.o

The above two commands can be linked together:

gcc  -shared  -fpic-  o  libmyhello.so  hello.c

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.

If you are compiling directly with the following method, connect:

$  gcc  -o Hello  main.c  -L.  -lmyhello

( 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. Note: "." Represents the current directory )

Execute Target Program:

$ ./hello

Error :

 while Object

Error: Unable to find the dynamic library file libmyhello.so. When the program runs, it will find the required dynamic library files, which are described in the following article. If found, loads the dynamic library, otherwise it will prompt similar errors to terminate the program. There are several ways to resolve:

1) We copy the file libmyhello.so to the directory/usr/lib and try again.

$  sudo  mv  libmyhello.so  /usr/lib$  -V

2) Now that the connector is searching for the directory specified by Ld_library_path, we can add the current directory to the environment variable

Export  ld_library_path=$ (Ld_library_path): $ (pwd)

3) write the current directory to/etc/ld.so.conf, and then execute the ldconfig-v command to write the dynamic library to the/etc/ld.so.cache file.

When set correctly, execute the./hello to execute the program.

You can see how it calls functions in a dynamic library.

Linux-vdso.so. 1 = (0x00007fffe8f9b000=/home/chenjw/testso/libmyhello.so (  0x00007fbe807d5000) libc.so. 6 =/lib/x86_64-linux-gnu/libc.so. 6 (0x00007fbe80410000/lib64/ld-linux-x86-. So.  2 (0x000055dc016c2000)

2.6 Search Path order when static library links:

LD is going to find the parameters in the GCC command-l

Look for GCC's environment variable Library_path

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

2.7 When a dynamic library is linked, the search path order is performed:

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

environment variable Ld_library_path the specified dynamic library search path;

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

The default dynamic library search path/lib;

The default dynamic library search path/usr/lib.

2.8 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

Transferred from: http://blog.csdn.net/CSqingchen/article/details/51546784

"Go" Linux under GCC build and use static libraries and dynamic library details

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.