How to compile dynamic libraries with GCC under Linux

Source: Internet
Author: User
Tags exit pack

This article mainly solves the following several questions

1 Why should I use a library?

2 Classification of libraries

3 Creating your own library

Maybe you still remember party was fresh when you were a beginner of Linux. Without a better package manager to solve dependencies, installing software under Linux would be a painful task. When you pack a bag, you may be prompted to pack a B bag, and when you try to find B package, you may be prompted to install the C package first. I have been such a thing to make a mess, so far a mention of rpm still lingering fear, scalp numbness. Say is bitten, ten years afraid of shy also cannot be too.

Linux has this many dependencies, one of the principles of development is really the work. The principle is: Try not to repeat what others have done. In other words, try to make the most of other people's work.

This involves how to effectively reuse the code.

1 Why should I use a library?

There are generally two ways to code reuse.

Paste Copy

This is the least technical content of a program. If the code is small, the workload can be tolerated, and if the code is large, this method is not advisable. Even if someone does this, who can guarantee that all the code is available?

And the emergence of the library is a good solution to this problem.

Library, is a kind of encapsulation mechanism, simply put all the source code compiled into the target codes after the package.

So how can the user know what kind of interface the library provides? Do you want to scan it with NM and other tools?

Don't worry, the developers of the library have done everything in the morning. In addition to the library containing the target code, www.Linuxidc.com typically provides a series of header files, which contain the library's interfaces. In order to make it easy for users, add a description of the use is almost perfect.

2 Classification of libraries

2.1 Classification of libraries

Depending on the link period, the library is divided into static and dynamic libraries.

The static library is linked in the link phase (as if it were nonsense, but this is the case), so the resulting executable file is not affected by the library, and even if the library is deleted, the program can still run successfully.

Unlike static libraries, dynamic library links are linked at the time the program is executed. So, even if the program is finished compiling, the library must remain on the system for the program to be invoked when it is run. (TODO: What does the link phase do when linking a dynamic library?)

2.2 Comparison of static and dynamic libraries

Link Static library In a sense is also a kind of paste copy, but it is the object of the operation of the target code rather than the source. Since the static library is linked, the library is embedded directly into the executable file, which creates two problems.

The first is that the system space is wasted. It is obvious to imagine that if multiple programs link to the same library, then each generated executable will have a copy of the library, which will inevitably waste the system space.

Moreover, err, even if the library is carefully debugged, it will inevitably be wrong. Once you find a bug in the library, it's more troublesome to save it. You must find the program that links the library and recompile it.

And the emergence of dynamic library is to make up for the static library of the above drawbacks. Because dynamic libraries are linked while the program is running, disk space is saved by keeping only one copy of the disk. If you find a bug or want to upgrade it is very simple, just use the new library to replace the original line.

So, is not the static library is useless?

Answer Yue: not also not also. There is no saying: existence is reasonable. Static library Since there is no annihilation in the surging history of the river, it must have its application. Imagine such a situation: if you use Libpcap library to make a program, to be run by people, and his system does not install Pcap library, how to solve it? The easiest way to do this is to link all the libraries you want to link to their static libraries when you compile the program, so You can run the program directly on someone else's system.

The so-called gain must be lost, because the dynamic library in the program is linked to the runtime, so the speed of the program and the link to the static library version is bound to discount. However, afterward, the lack of dynamic libraries relative to its benefits in the current hardware is simply negligible, so the linker in the link is generally preferred to link the dynamic library, unless the-static parameter to specify the link static library.

2.3 How can I tell if a program has links to dynamic libraries?

The answer is to use the file utility.

File program is used to determine the type of files, under the File command, all the files will be true to their true colours.

By the way, a trick. Sometimes in Windows under the browser to download tar.gz or tar.bz2 files, suffix name will become strange Tar.tar, to Linux some novice do not know how to unpack. But the file type under Linux is not affected by the file suffix name, so we can use the command file Xxx.tar.tar to look at the file type and then extract the appropriate parameters with tar.

In addition, can also use the program LDD utility to judge.

LDD is used to print information about all the dynamic libraries that are linked by the target program (specified by the command-line arguments), if the target program does not have a linked dynamic library, print "Not a dynamical executable", LDD use refer to manpage.

3 Creating your own library

3.1 Creating a dynamic library

Create a file hello.c that reads as follows:

#include

void Hello (void)

{

printf ("Hello worldn");

}

Compile the Hello.c-o libhello.so with the command gcc-shared into a dynamic library. As you can see, there is one more file libhello.so in the current directory.

[Leo@leo test]$ file libhello.so

Libhello.so:ELF 32-bit LSB Shared object, Intel 80386, version 1 (SYSV), not stripped

See, the file type is shared object.

Then edit a test file test.c, which reads as follows:

Int

Main ()

{

Hello ();

return 0;

}

This can be compiled:)

[Leo@leo test]$ gcc test.c

/tmp/ccm7w6mn.o:in function ' main ':

TEST.C: (. text+0x1d): Undefined reference to ' hello '

Collect2:ld returned 1 exit status

GCC could not find the Hello function at link time, compilation failed: (. The reason for this is hello in the library we created, if GCC can find it, just teach the hell!ok.

[Leo@leo test]$ gcc Test.c-lhello

/usr/lib/gcc/i686-pc-linux-gnu/4.0.0/.. /.. /.. /.. /i686-pc-linux-gnu/bin/ld:cannot Find-lhello

Collect2:ld returned 1 exit status

[Leo@leo test]$ gcc test.c-lhello-l.

[Leo@leo test]$

The first compilation of direct compilation, GCC by default will link to standard C library, but the symbol name Hello resolution does not come out, so the connection phase can not pass.

Now use GCC test.c-lhello-l. has been compiled successfully, the default output is a.out. Now try to run it:

[Leo@leo test]$./a.out

./a.out:error while loading shared libraries:libhello.so:cannot open Shared object file:no such file or directory

Hey, what's going on? Originally, although the link-time linker (dynamic linker) found libhello.so, the dynamic loader (dynamically loader, generally/lib/ld-linux.so.2) was not found. Let's look at the output of LDD:

[Leo@leo test]$ ldd a.out

Linux-gate.so.1 => (0xffffe000)

Libhello.so => not found

Libc.so.6 =>/lib/libc.so.6 (0x40034000)

/lib/ld-linux.so.2 (0x40000000)

Sure enough, see no, libhello.so => not found.

Linux provides us with two solutions:

1. You can add the current path to the/etc/ld.so.conf and then run the Ldconfig, or run ldconfig with the current path as the parameter (with root permissions only).

2. Add the current path to the environment variable Ld_library_path

Of course, if you think it will not cause confusion, you can directly copy the library into the/lib,/usr/lib/and other places (unavoidable, do also have permission), so that the linker and the loader can be accurate to find the library.

We use the second method:

[Leo@leo test]$ export ld_library_path=.: $LD _library_path

[Leo@leo test]$ ldd a.out

Linux-gate.so.1 => (0xffffe000)

Libhello.so =>./libhello.so (0x4001f000)

Libc.so.6 =>/lib/libc.so.6 (0x40036000)

/lib/ld-linux.so.2 (0x40000000)

Haha, this next ld-linux.so.2 can find libhello.so this library.

Now you can run it directly:

[Leo@leo test]$./a.out

Hello World

3.2 Creating a static library

Still use just the hello.c and test.c.

The first step is to generate the target file.

[Leo@leo test]$ gcc-c hello.c

[Leo@leo test]$ ls hello.o-l

-rw-r--r--1 Leo users 840 May 6 12:48 hello.o

The second step is to archive the target files.

[Leo@leo test]$ ar R libhello.a hello.o

Ar:creating LIBHELLO.A

OK,LIBHELLO.A is the static library we created, simple:

[Leo@leo test]$ file Libhello.a

Libhello.a:current AR Archive

The next line of command is to teach you how to link a static library in a program:

[Leo@leo test]$ gcc test.c-lhello-l.-static-o hello.static

Let's use the file command to compare the difference between a program that is linked with a dynamic library and a static library:

[Leo@leo test]$ gcc test.c-lhello-l.-O hello.dynamic

As mentioned earlier, the linker will default to link the dynamic library (this is libhello.so), so just remove the-static parameter from the previous command.

Verify with the file utility that the executable was generated as we requested:

[Leo@leo test]$ file Hello.static hello.dynamic

Hello.static:ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for Gnu/linux 2.6.6, statically linked, not Stripp Ed

Hello.dynamic:ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for Gnu/linux 2.6.6, dynamically linked (Uses Sha Red Libs), not stripped

You might as well practice LDD usage:

[Leo@leo test]$ ldd hello.static hello.dynamic

Hello.static:

Not a dynamic executable

Hello.dynamic:

Linux-gate.so.1 => (0xffffe000)

Libhello.so =>./libhello.so (0x4001f000)

Libc.so.6 =>/lib/libc.so.6 (0x40034000)

/lib/ld-linux.so.2 (0x40000000)

OK, there seems to be no problem, then compare the size first:

[Leo@leo test]$ ls-l hello. [ds]*

-rwxr-xr-x 1 Leo users 5911 May 6 12:54 hello.dynamic

-rwxr-xr-x 1 Leo users 628182 May 6 12:54 hello.static

See the difference, the link to the static library of the target program and Link Dynamic Library program is a huge monster!

Such a small program, it is difficult to see the difference in execution time, but for the sake of completeness, or look at the output bar:

[Leo@leo test]$ time./hello.static

Hello World

Real 0m0.001s

User 0m0.000s

SYS 0m0.001s

[Leo@leo test]$ time./hello.dynamic

Hello World

Real 0m0.001s

User 0m0.000s

SYS 0m0.001s

If the program is larger, the effect will be very obvious.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.