Shared (Dynamic) Library

A shared library is a collection of object files that are linked dynamically at runtime by the operating system.

1. Write Your Code:

Use the same source files as in the static library example.

2. Compile the Object Files with Position-Independent Code (PIC):

Compile your source files into position-independent object files.

gcc -c -fPIC mylib.c -o mylib.o

3. Create the Shared Library:

Use the gcc command to create the shared library (.so file).

gcc -shared -o libmylib.so mylib.o

4. Use the Shared Library:

Link the shared library to your program when compiling it.

C
// main.c
#include "mylib.h"

int main()
{
    hello();
    return 0;
}
gcc main.c -L. -lmylib -o myprogram

5. Run the Program with the Shared Library:

Ensure the shared library is in our library path or use the LD_LIBRARY_PATH environment variable to specify the path.

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:../myprogram

Explanation:

  • Headers (.h files): Contain function declarations and macro definitions to be shared between several source files.
  • Source (.c files): Contain the actual code of the functions.
  • Object files (.o files): Compiled code that is not yet linked into an executable.
  • Static library (.a file): Archive of object files.
  • Shared library (.so file): Dynamically linked library.

By following these steps, you can crea


te both static and shared libraries in C.


How Do I Create a Library in C?

Libraries are a collection of code that can be used by other programs. They promote code reuse and modularity. In C, we can create our own libraries. In this article, we will learn how to create a library in C.

Similar Reads

Creating a Library in C

In C, there are multiple methods using which we can create a library.:...

Static Library

A static library is a collection of object files that are linked into the program during the linking phase of compilation, resulting in a single executable file....

Shared (Dynamic) Library

A shared library is a collection of object files that are linked dynamically at runtime by the operating system....