static and dynamic libraries

static and dynamic libraries

Why use libraries in C?

Libraries in C are not unlike public libraries in cities, towns, or neighborhoods. A public library provides access to a multitude of information in various media forms to the public for access and use. Functions in a C library can be used and accessed by programmers to create several different programs.


As a programmer, you may find yourself using the same function or functions repeatedly. In this case, it is best to put this function or functions in a library to speed up the compilation of the program. C libraries store files in object code; during the linking phase of the compilation process (?Compilation Process) files in object code are accessed and used. It is faster to link a function from a C library than to link object files from a separate memory sticks or discs.

How to create and use libraries in Linux:

Static libraries:

To create a Static library, you start by assembling all your library files into one file. They should be object files, ending with the extension “.o” (example: foo.o). You will place them in your static library, which should end with the extension “.a” and begin with the letters “lib” (for example: libwhatever.a). To do this, you will need to use a program called “ar.” How do we obtain those files with the .o extension?


First, we need to compile our .c files in such a way that they pass through the preprocessor, the compiler proper and the assembler, but we will stop the process right before the linking stage. To do this, we will compile our files using:

gcc -c *.c        

This command will compile all the files with the “.c” extension and create object code in “.o” extension files, but will stop short of the linking phase. For example:

$ls *.c 
file1.c file2.c file3.c
$gcc -c *.c
file1.c file 1.o file2.c file2.o file3.c file3.o        

Now we can create our library using the archiver: “ar” command:

ar rc libwhatever.a *o        

When we run this command, our Static library , “libwhatever.a” will be created. Now we can simply index our library using:

ranlib libwhatever.a        

This will make it easier and faster to find what you need in your new Static library!

Use your library to store important programs that you use often or in various programs so that you don’t have to repeat the same work over and over.

Use your Static library:

Add the name of the library to the list of object files you will provide to the linker using the “-l” flag:

gcc main.o -l -lwhatever -o program        

Notice that when referring to the library, you drop the initial “lib” prefix as well as the “.a” extension.

Dynamic libraries:

To create a Dynamic library, start by compiling your “.c” files with the following command:


gcc -c fPIC *.c        

This command will take your “.c” files and return object code files ending in “.o”:

$ ls
file1.c file2.c file3.c headerfile.h
$ gcc -c fPIC *.c
file1.c file1.o file2.c file2.o file3.c file3.o headerfile.h        

Now we will create our Dynamic library from these files:

gcc -shared -o libwhatever.so *.o        

Our Dynamic library is now created. How can we use it?

If we want to use a program, “printhappyface” in our file1.c file to run a program in our main1.c file, we can compile our main1.c file in the following way:

gcc -L. main1.c -lwhatever -o printhappyface        

By adding -L., the linker will look for a library in the current directory. Although we wrote “-lwhatever” the linker will find the library libwhatever.so and use the information found there to produce “printhappyface”.

Now you can add the environment variable to the library path (so it can be found):

$LD_LIBRARY_PATH=.:$LD_LIBRARY_PATH        

Finally, you can run your program:

$./printhappyface
:-)        

Static and Dynamic Libraries

When a C program is compiled, the compiler generates object code. After generating the object code, the compiler also invokes linker. One of the main tasks for linker is to make code of library functions (eg printf(), scanf(), sqrt(), ..etc) available to your program. A linker can accomplish this task in two ways, by copying the code of library function to your object code, or by making some arrangements so that the complete code of library functions is not copied, but made available at run-time.

Static Linking and Static Libraries?is the result of the linker making copy of all used library functions to the executable file. Static Linking creates larger binary files, and need more space on disk and main memory. Examples of static libraries (libraries which are statically linked) are,?.a?files in Linux and?.lib?files in Windows.

Steps to create a static library?Let us create and use a Static Library in UNIX or UNIX like OS.

1.?Create a C file that contains functions in your library.

/* Filename: lib_mylib.c */

#include <stdio.h>

void fun(void)

{

??printf("fun() called from a static library");

}

We have created only one file for simplicity. We can also create multiple files in a library.

2.?Create a header file for the library

/* Filename: lib_mylib.h */

void fun(void);

3.?Compile library files.

 gcc -c lib_mylib.c -o lib_mylib.o         

4.?Create static library. This step is to bundle multiple object files in one static library (see?ar?for details). The output of this step is static library.

 ar rcs lib_mylib.a lib_mylib.o         

5.?Now our static library is ready to use. At this point we could just copy lib_mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory.

Let us create a driver program that uses above created static library.

1.?Create a C file with main function

/* filename: driver.c? */

#include "lib_mylib.h"

void main()?

{

??fun();

}

2.?Compile the driver program.

gcc -c driver.c -o driver.o        

3.?Link the compiled driver program to the static library. Note that -L.?is used to tell that the static library is in current folder (See?this?for details of -L and -l options).

gcc -o driver driver.o -L. -l_mylib        

4.?Run the driver program

./driver 
fun() called from a static library        

Following are some important points about static libraries.

1.?For a static library, the actual code is extracted from the library by the linker and used to build the final executable at the point you compile/build your application.

2.?Each process gets its own copy of the code and data. Where as in case of dynamic libraries it is only code shared, data is specific to each process. For static libraries memory footprints are larger. For example, if all the window system tools were statically linked, several tens of megabytes of RAM would be wasted for a typical user, and the user would be slowed down by a lot of paging.

3.?Since library code is connected at compile time, the final executable has no dependencies on the library at run time i.e. no additional run-time loading costs, it means that you don’t need to carry along a copy of the library that is being used and you have everything under your control and there is no dependency.

4.?In static libraries, once everything is bundled into your application, you don’t have to worry that the client will have the right library (and version) available on their system.

5.?One drawback of static libraries is, for any change(up-gradation) in the static libraries, you have to recompile the main program every time.

6.?One major advantage of static libraries being preferred even now “is speed”. There will be no dynamic querying of symbols in static libraries. Many production line software use static libraries even today.

Dynamic linking and Dynamic Libraries?

Dynamic Linking doesn’t require the code to be copied, it is done by just placing name of the library in the binary file. The actual linking happens when the program is run, when both the binary file and the library are in memory. Examples of Dynamic libraries (libraries which are linked at run-time) are,?.so?in Linux and?.dll?in Windows.

We will soon be covering more points on Dynamic Libraries and steps to create them.

This article is compiled by?Abhijit Saha?and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

要查看或添加评论,请登录

Anas Ferchichi的更多文章

  • Face Detection

    Face Detection

    What is face detection Face detection is a computer vision technique that involves identifying and locating human faces…

  • Ethical Challenges in AR / VR

    Ethical Challenges in AR / VR

    The Impact of Virtual Reality and Immersive Experiences on Users and Society Virtual reality (VR) and augmented reality…

  • Unity Interface

    Unity Interface

    What is Unity Unity is a popular game development engine that allows developers to create amazing 2D and 3D games. The…

  • What's the Big Deal?

    What's the Big Deal?

    What does “STEM” mean? Let’s start with a basic question: Exactly what does STEM mean? It's a term many are familiar…

  • My first postmortem

    My first postmortem

  • What happens when you type google.com in your browser and press Enter !!!

    What happens when you type google.com in your browser and press Enter !!!

    Web Stack A Web stack is the collection of software required for Web development. At a minimum, a Web stack contains an…

  • knowledge - IoT

    knowledge - IoT

    What is IoT?: The Internet of Things (IoT) describes the network of physical objects—“things”—that are embedded with…

  • Share your knowledge - Recursion

    Share your knowledge - Recursion

    What is recursion? The process in which a function calls itself directly or indirectly is called recursion and the…

  • How object and class attributes work

    How object and class attributes work

    A class is a custom data type, In python, we can create custom classes that are fully integrated and that can be used…

  • Static Libraries in C

    Static Libraries in C

    In the previous blog post we learned about Compiling Process and that in the linking part of it compiler connects…

社区洞察

其他会员也浏览了