日期:2014-05-16  浏览次数:20627 次

Linux使用静态库

以下一个简单的小例子来学习如何使用静态库

hello.c  hello.h  main.c  Makefile

总共4个文件,逐一来看

hello.h

#ifndef _HELLO_H
#define _HELLO_H
extern int test(void);
#endif


hello.c

#include <stdio.h>
int test(void)
{
printf("hello!\n");
}


main.c

#include <stdio.h> 
#include "hello.h"
int main()
{
test();
return 0;
}


Makefile

EXEC:= test
SRC:= main.c
LIB_SRC:= hello.c
LIB:= libhello.a


#all: $(EXEC)


$(EXEC): $(LIB)
gcc -o $@ $(SRC) -L. $(LIB)


$(LIB): $(patsubst %.c, %.o, $(LIB_SRC)) 
ar cr $@ $<


.PHONY: clean
clean:
rm *.o *.a $(EXEC)


make 之后就可以了。