Create and use a Linked Library in Linux

Source: Internet
Author: User

Under the/usr/lib directory, we can see many file formats, such as libxxx. So and libxxx.. Libxxx. A is called a static link library or a link library. libxxx. So is called a shared link library or a dynamic link library.

=== Archives ===
We often use libraries when programming. For example, when we write a network capture program, we use Libnet library when you use libpcap and write the network packet sending function.
We only need to add the Linked Library during compilation.
GCC test_pcap.c-lpcap
The compiler automatically adds lib to the front of the pcap, and adds. A to the end, that is, to link the Libpcap. A library file.

If you can write your own libraries, let's introduce how to create your own Link Library.

. A is called archive. It is generated using the AR command. It archives some. O files together, just like the. Lib file in windows. Therefore, when we use the Linked Library, it is actually one or some. O files in linked. A, which is the same as GCC compilation. In addition, you must note that you need to put the Linked Library at the end.
Gcc-O test_pcap test_pcap.o-lpcap
This is mainly because the linker will automatically look for the previous symbol in the future. If gcc-O test_pcap-lpcap test_pcap.o is used. The link will fail, because Linker will not find some functions about libpcap in test_pcap.o.

I almost forgot one important thing: how to create a Linked Library:
Ar Cr libtest. A test1.o test2.o
As mentioned above, the. A file is an archive of the. o file.

=== Shared libraries ===
The shared library is similar to the Link Library mentioned above, but there are some differences between them. First, if a program links to the shared library, there is no corresponding code in the final generated executable code, and there is only one shared library reference, which reduces the size of the executable file, it takes some time to get the corresponding code through reference.
Using a shared library can reduce the size of executable files and facilitate database version upgrades without re-compiling the code.

So how to create a shared library? Let's look at an example:
Gcc-FPIC-shared-O libtest. So test1.o test2.o
Is it easy?

-FPIC allows the output object module to be generated in the form of relocated addresses.
-Shared specifies to generate the corresponding dynamic link library file libtest. So for the corresponding source file.

The use of shared libraries can be divided into display call and implicit call.
==== Implicit call ====
Implicit call is similar to the usage of the linked library above:
Gcc-O app. O-L.-ltest

In this case, if the. A and. So files exist in the directory specified by-L, which file should linker link?
In fact, you need to know the link sequence of linker. If you find a directory, only. A and. so, select the existing file. For example. a, then link. file. If both files exist, the link. So file is selected by default.
Of course, there is another situation that requires attention, that is, when it is static, it uses. A to link.
Gcc-static-O app. O-L.-ltest

As mentioned above, we use-L to add a temporary path for the library search path. In addition, we can modify the LD_LIBRARY_PATH environment variable to add a path.
Export LD_LIBRARY_PATH = "/usr/lib/old:/opt/lib"

==== Display call ====
In fact, the displayed call is actually used to dynamically load and uninstall libraries in program code.
Dynamic Link Library, using lD. So for loading.

# Include <dlfcn. h>

Void * dlopen (const char * filename, int flag );
Void * dlsym (void * handle, const char * symbol );
Int dlclose (void * handle );

Process:
Void * handle = dlopen ("libtest. So", rtld_lazy );
Void (* test) () = dlsym (handle, "my_function ");
(* Test )();
Dlclose (handle );

The following is an example program in man dlopen:
/* Filename: dl_call.c */
# Include <stdio. h>
# Include <stdlib. h>
# Include <dlfcn. h>

Int main (void)
{
Void * handle;/* 'handle' pointer of shared library */
Double (* cosine) (double);/* points to the function in the shared library */
Char * error;/* record the error message of dynamic loader */

/* Open shared library 'lib '*/
Handle = dlopen ("libm. So", rtld_lazy );
If (! Handle ){
Fprintf (stderr, "% s/n", dlerror ());
Exit (1 );
}

Dlerror ();/* clear any existing Error */

/* Find the "Cos" function in the shared library to which handle points,
* And return its memory address
*/
Cosine = dlsym (handle, "Cos ");
If (error = dlerror ())! = NULL ){
Fprintf (stderr, "% s/n", error );
Exit (1 );
}

/* Indirect function call (indirect call of function pointers ),
* Call the specified function
*/
Printf ("% F/N", (* cosine) (2.0 ));
Dlclose (handle );
Return 0;
}

Because the dlopen () function is used, it must be linked to libdl during compilation.
$ Gcc-O dl_call dl_call.c-LDL
The above practices are equivalent:
Printf ("% F/N", cos (2.0 ));

If the shared library is written in C ++, We need to declare it in the following format if we use the shared library in a C program:
Extern "C" void Foo ();
For more information about C ++ dlopen, see C ++ dlopen mini howto in reference.

Libdl is widely used. Many software makes some of its functional modules into a shared library and loads them into dlopen () for use. Because the shared library is "Interchangeable, therefore, you can use libdl to implement the "plug-ins" function.

=== Reference ===
C ++ dlopen mini howto
Http://www.isotton.com/devel/docs/C++-dlopen-mini-HOWTO/C++-dlopen-mini-HOWTO.html
Http://www.linuxsir.org/bbs/printthread.php? T = 266890
Program links and loading and Implementation of Dynamic Links in Linux
Http://www.ibm.com/developerworks/cn/linux/l-dynlink/index.html

=== Questions ===
1. If the. A and. So files exist in the directory specified by-L, which file should linker link?

=== Appendix ====
One major advantage of a shared library is that it saves space on the system where
The program is installed. If you are installing 10 programs, and they all make use of
Same shared library, then you save a lot of space by using a shared library. If you used
Static archive instead, the archive is already ded in all 10 programs. So, using shared
Libraries saves disk space. It also reduces download times if your program is being
Downloaded from the web.
A related advantage to shared libraries is that users can upgrade the libraries
Upgrading all the programs that depend on them. For example, suppose that you
Produce a shared library that manages HTTP connections. Pipeline programs might
Depend on this library. If you find a bug in this library, you can upgrade the Library.
Instantly, all the programs that depend on the library will be fixed; you don't have
Relink all the programs the way you do with a static archive.
Those advantages might make you think that you shoshould always use shared
Libraries. However, substantial reasons exist to use static archives instead. The fact that
An upgrade to a shared library affects all programs that depend on it can be a disadvantage.
For example, if you're developing mission-critical software, you might rather Link
To a static archive so that an upgrade to shared libraries on the system won't affect
Your program. (otherwise, users might upgrade the shared library, thereby breaking your
Program, and then call your customer support line, blaming you !)
If you're not going to be able to install your libraries in/lib or/usr/lib, you
Shocould definitely think twice about using a shared library. (You won't be able to install
Your libraries in those directories if you have CT users to install your software
Administrator privileges.) In particle, the-wl,-rpath trick won't work if you don't
Know where the libraries are going to end up. And asking your users to set
LD_LIBRARY_PATH means an extra step for them. Because each user has to do this
Individually, this is a substantial additional burden.
You'll have to weigh these advantages and disadvantages for every program you
Distribute.

Reference: http://blog.csdn.net/zhoujunyi/archive/2007/12/12/1930864.aspx

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.