Horje
How to Create a Static Library in C?

In C, we can create our own libraries that contains the code for the functions or macros that we may need very often. These libraries can be then used in our programs. In this article, we will learn how to create a custom static library and use it with GCC compiler.

What is a Static Libraries in C?

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. The static libraries code is copied to the given program before creating the executable file.

Creating Static Libary in C

Follow the given steps to create a static libary:

Step 1: Define the Header File

Create the header file that declares the functions to be used from the library. For example, mylib.h.

mylib.h

C
#ifndef MYLIB_H
#define MYLIB_H

void hello();

#endif // MYLIB_H

Step 2: Create the Source File for the Header

Create the source file that implements the functions declared in the header file. For example, mylib.c.

mylib.c

C
#include "mylib.h"
#include <stdio.h>

void hello() { printf("Hello, World!\n"); }

Step 3: Compile the Object File

Compile the source file into an object file (.o or .obj). For GCC, use the following command

gcc -c mylib.c -o mylib.o

Step 4: Create the Static Library

Use the ar (archiver) command to create the static library (.a file).

ar rcs libmylib.a mylib.o

After this, you can use the library in your program. Take the below example

Example

C++
#include "mylib.h"

int main() {
    hello();
    return 0;
}


Output

Hello, World!

But to compile it with GCC, we need to pass some additional arguments:

gcc main.c -L. -lmylib -o myprogram



Reffered: https://www.geeksforgeeks.org


C Language

Related
C Program to Implement Binomial Heap C Program to Implement Binomial Heap
Maximum Product Subarray in C Maximum Product Subarray in C
remquo() Function in C remquo() Function in C
Kahn’s Algorithm in C Language Kahn’s Algorithm in C Language
Counting Set bit in C Counting Set bit in C

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
21