Thursday, February 05, 2009

Creating Static Libraries in Linux

add.c
=====

int add(int a, int b) {
return a+b;
}

int sub(int a, int b) {
return a-b;
}

>>gcc -c add.c // creates add.o


mul.c
=====

int mul(int a, int b) {
return a*b;
}

int div(int a, int b) {
return a/b;
}

>>gcc -c mul.c // Creates mul.o


Creating Archive
================

ar cr libaddmul.a add.o mul.o // Create and replace the obj files in the archive

ranlib libaddmul.a // generate index to archive

nm libaddmul.a // list symbols from object files

How to use the Static Library
=============================

math.c
======

#include "stdio.h"
#include "addmul.h"

int main() {
printf(" 3 + 5 = %d\n", add(3, 5));
printf(" 3 - 5 = %d\n", sub(3, 5));
printf(" 3 * 5 = %d\n", mul(3, 5));
printf(" 3 / 5 = %d\n", div(3, 5));
return 0;
}

addmul.h
========

extern int add(int, int);
extern int sub(int, int);
extern int mul(int, int);
extern int div(int, int);

gcc -o math math.c -L((libaddmul.a path)) -laddmul // compile math.c with addmul library

1 comment:

Reemus Kumar said...

thanks for the comment