[C / C ] Create a library of C – Create a library in C

When working with C, if there is some content that you regularly use and do not want to rewrite many times, Please create a library file containing the function. This article will help you do it!

Content – Table of content
Creating library file – Create library file
Using homemade library – Using self library

Creating library file

To create a library file, What else you do not write code with your normal. You create a file with the extension .h and write the content you want to. For example, to create a library mylibrary.h contains functions and factorial factorial, jaw conversion swap, jaw sorted quickly quicksort.

long factorial(int n) {
     
    int i;
    long result = 1;
    for (i = 2; i <= n; i++){
        result *= i;
    }
     
    return result;
}
 
void swap(int *a, int *b){
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
 
void quickSort(int *a, int l, int r) {
    srand(time(NULL)); 
    int key = a[l + rand() % (r-l+1)]; 
    int i = l, j = r;
  
    while(i <= j) {
        while(a[i] < key) i++;      
        while(a[j] > key) j--;     
        if(i <= j) {
            if (i < j)
                swap(&a[i], &a[j]);
            i++;
            j--;
        }
    }
 
    if (l < j) quickSort(a, l, j); 
    if (i < r) quickSort(a, i, r);
}

Using homemade library

Now we just use the library. The user should also be noted, have 2 use.
How to 1: If you've created a library to the same directory as the other code file in the library call will be #include “mylibrary.h”. In this case, when you use the library you need to copy this file and the file code.

How to 2: If you do not want to trouble the way 1, Please copy the file you just created on /usr/include with Linux, on windows, then copy the folder that contains the library, for dev-C is in C:Program FilesDev-CppMinGW32include. When you use like any other library by #include <mylibrary.h> .

In the illustration below your file to the same directory.

#include <stdio.h>
#include "mylibrary.h"
 
int main (int argc, char *argv[])
{
 
    printf("5! = %ldn",    factorial(5));
 
    int i, arr[] = { 40, 10, 100, 90, 20, 25 };
    quickSort(arr, 0, 5);
    printf("after sort, array is: n");
    for (i=0; i<6; i++)
        printf ("%d ", arr[i]);
    printf("n");
     
    return 0;
}

create library in C