C Static Libraries

Why use libraries?

  • Structure and organization of the default code, avoiding having to perform an analysis on where to place the different application files (resources, controllers, views, models, etc.).
  • Code reuse. Avoid code duplication.
  • Agility and speed in development. Thanks to the reuse of code we achieve faster development, since we will not waste time developing new functionalities.
  • Lower cost in development. Finishing a project earlier means that dedication is less and the cost of a project decreases.
  • Good development practices with the use of patterns. They are based on design patterns, which indicate guidelines on how to solve a specific problem that has already occurred before.
  • Minimizing errors and making it easier to solve possible errors that you may have will always be better than developing it from scratch.
  • Ease of finding code that already covers functionalities of a particular development.
  • Facilitates collaboration with other developers.
  • It facilitates maintenance when the application needs to be updated or an evolutionary one needs to be carried out, taking less time and reducing the total cost.

How to create them

ar rc libutil.a util_file.o util_net.o util_math.o

ranlib libutil.a

How they work and How to use them

Example of creating a simple library in C

sum.c

/*
* FILE: suma.c
*/

int suma(int n1, int n2){
return n1+n2;
}

resta.c

/*
* FILE: resta.c
*/

int resta(int n1, int n2){
return n1-n2;
}
gcc -c suma.c
gcc -c resta.c
ar -cvr libcalculadora.a suma.o resta.o
/tmp/libcalculadora$ ar -t libcalculadora.a
suma.o
resta.o

calculadora.h

/*
* FILE: calculadora.h
*/

#ifndef CALCULADORA_H
#define CALCULADORA_H

#include<stdio.h>
#include<stdlib.h>

int suma(int,int);
int resta(int,int);

#endif
/*
* FILE: calculadora.c
*/
#include "calculadora.h"

int main(int argc, const char *argv[]){
int (*ptr_fc)(int,int);
int n1 = atoi(*(argv+1));
int n2 = atoi(*(argv+3));
char op = *(*(argv+2));

switch(op){
case '+':
ptr_fc = suma;
break;
case '-':
ptr_fc = resta;
break;
default:
printf("Opción incorrecta!!\n");}

printf(">>> %d %c %d = %d\n", n1, op, n2, (*ptr_fc)(n1,n2));
return 0;}
gcc calculadora.c -L/tmp/libcalculadora -lcalculadora

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store