---
title: "创建一个linux 静态库"
author: "qvb3d"
date: "2012-06-13T10:23:12Z"
tags: []
categories: ["编程语言"]
slug: "linux"
draft: false
lastmod: "2012-06-13T10:23:12Z"
id: 1559604
url: "https://qvb3d.iteye.com/blog/1559604"
---

创建一个linux 静态库

1.我们先写一个简单的函数

  maxh.h   
 

```
int max(int a,int b);
```

   
  maxh.c

 

```
int max(int a,int b)
{
 return (a>b)?a:b;
}
```

 

  再写一个调用的

  testmain.c

 

```
#include <stdio.h>
#include "maxh.h"
int main(int argc,char *argv[])
{
int a,b;
printf("\nPlease input two num\n");
scanf("%d%d",&a,&b);
printf("\nThis Max is %d\n",max(a,b));
return 0;
}
```

 

 

2.写Makefile

 

```
CC=gcc
AR=ar
ALLOBJSRC=maxh
ALLOBJ=$(ALLOBJSRC).o
LIB_A=lib$(ALLOBJSRC).a
TARGET=testmain
MAINPRO=$(TARGET).o
all: $(ALLOBJ) $(MAINPRO)
	$(AR) -rcs $(LIB_A) $(ALLOBJ)
	$(CC) $(MAINPRO) -o $(TARGET) -I. -L. -l$(ALLOBJSRC)
$(ALLOBJSRC).o: $(ALLOBJSRC).c $(ALLOBJSRC).h
	$(CC) -c -I. -o $@ $<
$(MAINPRO): $(TARGET).c
	$(CC) -c -I. -o $@ $<
clean: $(ALLOBJ)
	rm -rf $(LIB_A) $(ALLOBJ) $(TARGET) $(MAINPRO)
#ar cs libmy.a  //create library
#ar rs libmy.a  xxx.o  //add module to library
#ar t libmy.a   //display module library
#ar d libmy.a   xxx.o  //delete module from library
```

   
  make

 

  ./testmain