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

Getting Started with JTAG Boundary Scan

Benefits of prototyping without assets

Property Testing our Base58Check Encoder with an External Oracle

Part 1. GenServer — Elixir/OTP

Create Shortcuts (Aliases) for Git

TrackId: Infixing trackBy capabilities to *ngFor in a centralised way across your Angular…

TDD: A Practice to (Hopefully) Prevent Bugs

Domain Oriented Data Architecture — Data Mesh

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

MVC Design Pattern + Clean ABAP

Fixing AWS Upload Error

Node.js Rest CRUD API with MySQL Part 1

Installing SQL Server and Microsoft SQL Server Management Studio on Windows Server 2019 VM.