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.

STEP 1: Define header file.

Create the source files for your library. For example, mylib.c and mylib.h.
mylib.h

C++
#ifndef MYLIB_H

#define MYLIB_H

void hello();

#endif // MYLIB_H

STEP 2: Create Source File for header

C
#include <stdio.h>
#include "main"
using namepace std;

void hello() {
  cout << "Hello World";
}


STEP 3. Compile the Object Files:

Compile our source files into object files (.o or .obj).

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

STEP 5. Use the Static Library:

Link the static library to our program when compiling it.

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

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

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....