우선 리눅스에서 라이브러리는 다른 프로그램에서 사용 할 수 있도록 미리 만들어진 하나이상의 서브 루틴이나 함수들이 모여있는 파일이다.

라이브러리 종류는 정적 라이브러리(static library=>.a파일)와 공유 라이브러리(shared library=>.so파일)이 있다. 둘다 장단점이 명확하지만 주로 라이브러리는 배포하기 위한 목적성을 갖기 때문에 대부분 .so형태로 만들어서 사용 된다.

간단한 예제를 통해 계산기 기능을 가지고 있는 정적 라이브러리와 동적 라이브러리를 만들어 보자.

<라이브러리를 만들 기 위한 큰그림

**[sum.h]**

#ifndef __SUM__H

#define __SUM__H

int sum(int a, int b);

#endif
**[sum.c]**

#include"sum.h"

#include<stdio.h>

int sum(int a, int b){

printf("This is sum function\\n");

return a+b;

}
**[sub.h]**

#ifndef __SUB__H

#define __SUB__H

int sub(int a, int b);

#endif
**[mul.h]**

#ifndef __MUL__H

#define __MUL__H

int mul(int a, int b);

#endif
**[mul.c]**

#include"mul.h"

#include<stdio.h>

int mul(int a, int b){

printf("This is Mul function\\n");

return a*b;

}
**[div.h]**

#ifndef __DIV__H

#define __DIV__H

int div(int a, int b);

#endif
**[div.c]**

#include"div.h"

#include<stdio.h>

int div(int a, int b){

printf("This is Div Function\\n");

if(b==0)

return 0;

return a/b;

}
**[main.c]
#include "sum.h"

#include "sub.h"

#include "mul.h"

#include "div.h"

#include<stdio.h>

int main(void){

printf("%d\\n",sum(10,10));

printf("%d\\n",sub(100,10));

printf("%d\\n",mul(10,10));

printf("%d\\n",div(10,10));

return 0;

}**

이제 재료가 준비가 되었으니 프로그램을 만들어보자.

1. 정적 라이브러리

정적 라이브러리는 라이브러리를 사용하는 프로그램과 함께 컴파일 된다. 프로그램의 크기가 커지게 되고 해당 라이브러리를 여러 프로그램에서 사용한다면 각각의 프로그램 마다 자신들의 코드영역에 코드를 넣기 때문에 비효율이 발생한다. 하지만 장점은 이식성이 좋고 속도가 공유 라이브러리에 비해 빠르다.

정적 라이브러리를 만드는 방법

gcc -c sum.c sub.c mul.c div.c (-c 옵션은 링크를 안하고 컴파일만 하는 옵션)