C Static Libraries

Why use libraries?

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

--

--

--

Developing in Holberton School

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

A quick overview of the implementation of a fast spelling correction algorithm

Software Architecture — The Monolithic Approach

Weihai Huadong Sees High Growth By Utilizing Morpheus.Network’s Supply Chain Platform

what algorithms are applied in the auto tuning of PID block in simulink?

Algorithms: befriend your enemy

Mutant Cats Newsletter

When and why use multiple K8s namespaces

Data Science Needs Refactoring, A Tutorial, Case Study, Tips & Tricks

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
Gonzalo Andres Tarazona Montenegro

Gonzalo Andres Tarazona Montenegro

Developing in Holberton School

More from Medium

C#/VB.NET: Merge Multiple Excel Workbooks or Worksheets into One

Mapping Friendship in dotnet (and many to many relations entity framework core)

c++ course

Keyed Dependency Injection using .NET