Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to compile dynamic Library with GCC under Linux

2025-01-20 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to compile a dynamic library with GCC under Linux". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to compile a dynamic library with GCC under Linux".

This paper mainly solves the following problems.

1 Why use libraries?

2 classification of libraries

3 create your own library

Maybe you still have a fresh memory of what happened when you first learned Linux. If there is not a better package manager to solve the dependency, installing software under Linux will be a very painful task. When you pack package a, you may be prompted to install package b first, and when you try to find package b, you may be prompted to install package c first. I have been so haunted by such a thing that I still have lingering fears and numbness at the mention of rpm. It is not too much to say that once bitten by a snake, it is not too much to be afraid of wells and ropes for ten years.

One of the development principles plays an important role in why there are so many dependencies in Linux. The principle is: try not to repeat what others have already done. In other words, try to make full use of the fruits of other people's labor.

This involves how to reuse the code effectively.

1 Why use libraries?

There are generally two ways to reuse code.

Paste and copy

This is the least technical solution. If the code is small, the workload is tolerable, and if the code is large, this approach is not desirable. Even if someone wants to do so, who can guarantee that all the code is available?

The emergence of the library solves this problem very well.

Library is a kind of encapsulation mechanism, which simply compiles all the source code into a package after being compiled into object code.

So how can users know what kind of interface the library provides? Do you have to scan one by one with tools such as nm?

Don't worry, the developers of the library have already done everything. In addition to the library that contains the object code, www.Linuxidc.com generally provides a series of header files, which contain the interface of the library. For the convenience of users, add a description of the use of almost perfect.

2 classification of libraries

2.1 Classification of libraries

According to the link period, the library can be divided into static library and dynamic library.

The static library is linked during the linking phase (it seems like nonsense, but that's the way it is), so the generated executable is not affected by the library, and even if the library is deleted, the program can still run successfully.

Unlike static libraries, links to dynamic libraries are linked when the program is executed. Therefore, even if the program is compiled, the library must remain on the system for call when the program is running. (TODO: what exactly does the linking phase do when linking dynamic libraries)

2.2 comparison between static library and dynamic library

In a sense, a linked static library is also a kind of paste and copy, but it operates on the object code rather than the source code. Because after the static library is linked, the library is directly embedded in the executable file, which brings two problems.

First of all, the system space is wasted. This is obvious. Imagine that if multiple programs link to the same library, each generated executable will have a copy of the library, which is bound to waste system space.

Moreover, people are not saints, even if it is a carefully debugged library, it is inevitable that there will be mistakes. Once you find that there is bug in the library, it will be troublesome to save it. The programs that link to the library must be found one by one and then recompiled.

The emergence of dynamic library makes up for the above disadvantages of static library. Because the dynamic library is linked while the program is running, only one copy needs to be kept on the disk, thus saving disk space. If you find bug or it's easy to upgrade, just replace the old one with a new library.

So, is the static library useless?

Answer: no and no. There is a saying: existence is reasonable. Since the static library has not been lost in the surging history, it must have the opportunity to display its talents. Imagine a situation like this: what if you write a program with the libpcap library and want to run it for someone who does not have the pcap library installed on his system? The easiest way is to compile the program by linking all the libraries you want to link to their static libraries, so that you can run the program directly on someone else's system.

As the saying goes, there are gains and losses, precisely because the dynamic library is linked when the program is running, so the running speed of the program is bound to be reduced compared with the version of the linked static library. However, the shortcomings of the dynamic library are negligible relative to its benefits in today's hardware, so the linker generally gives priority to linking the dynamic library when linking, unless the-static parameter is used to specify the link static library.

2.3 how to determine whether a program has a linked dynamic library?

The answer is to use the file utility.

The file program is used to determine the file type, and all files will be exposed under the file command.

A technique, by the way. Sometimes in windows to download tar.gz or tar.bz2 files with a browser, the suffix will become a strange tar.tar, to Linux some novices do not know how to decompress. However, the file type under Linux is not affected by the file suffix, so we can first look at the file type with the command file xxx.tar.tar, and then extract it with tar plus the appropriate parameters.

In addition, it can be judged with the help of the program ldd utility.

Ldd is used to print information about all dynamic libraries linked by the target program (specified by command line parameters). If the target program does not have a linked dynamic library, print "not a dynamic executable". For the use of ldd, please refer to manpage.

3 create your own library

3.1 create a dynamic library

Create the file hello.c, which is as follows:

# include

Void hello (void)

{

Printf ("Hello World\ n")

}

Compile to a dynamic library with the command gcc-shared hello.c-o libhello.so. As you can see, there is an extra 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.

Edit another test file, test.c, as follows:

Int

Main ()

{

Hello ()

Return 0

}

Now you can compile:)

[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 when linking, and the compilation failed: (. The reason is that hello is in the library we created ourselves, and it will be damned if gcc can find it! Ok, keep up your efforts.

[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] $

When compiling directly for the first time, gcc will link to the standard c library by default, but the symbolic name hello cannot be parsed, so the connection phase cannot be passed.

Now use gcc test.c-lhello-L. It has been compiled successfully and 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? It turns out that although the dynamic linker found the dynamic library libhello.so, the dynamic loader (dynamic loader, usually / lib/ld-Linux.so.2) did not find it. 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, libhello.so = > not found.

Linux provides us with two solutions:

1. You can add the current path to / etc/ld.so.conf and run ldconfig, or you can run ldconfig with the current path as a parameter (with root permission).

two。 Add the current path to the environment variable LD_LIBRARY_PATH

Of course, if you don't think it will cause confusion, you can copy the library directly into a location such as / lib,/usr/lib/ (inevitably, you need permission to do so), so that both the linker and loader can find the library accurately.

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, now ld-Linux.so.2 can find the library of libhello.so.

Now you can run it directly:

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

Hello World

3.2 create a static library

Still use the same hello.c and test.c as before.

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 file the target document.

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

Ar: creating libhello.a

OK,libhello.an is the static library we created. Let's make it simple:)

[leo@leo test] $file libhello.a

Libhello.a: current ar archive

The following command teaches you how to link static libraries in your program:

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

Let's use the file command to compare the difference between programs linked with dynamic and static libraries:

[leo@leo test] $gcc test.c-lhello-L. -o hello.dynamic

As mentioned earlier, the linker links the dynamic library by default (in this case, libhello.so), so just remove the-static parameter from the previous command.

Use the file utility to verify that the executable is 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 stripped

Hello.dynamic: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.6, dynamically linked (uses shared libs), not stripped

By the way, practice the use of ldd:

[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, so 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 target program that links the static library is a behemoth compared to the program that links the dynamic library!

It's hard to see the difference in execution time for such a small program, but for completeness, take a look at the output of time:

[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 relatively large, the effect should be obvious.

Thank you for your reading, the above is the content of "how to compile dynamic libraries with GCC under Linux". After the study of this article, I believe you have a deeper understanding of how to compile dynamic libraries with GCC under Linux. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report