首页 > 代码库 > makefile范例

makefile范例

单个文件夹下,指定源文件进行编译,更改头文件后会重新编译

srcs=src1.c src2.c prog.c
objs:=$(srcs:.c=.o)
deps:=$(srcs:.c=.d)

CFLAGS=-c -g -Wall

prog:$(objs)
	gcc -o prog $^

-include $(deps)
$(objs):%.o:%.c
	gcc $(CFLAGS) -MMD -MP -MF"$(@:%.o=%.d)" -o $@ $<


.PHONY: clean
clean:
	rm -rf prog *.o *.d
单个文件夹下,编译当前文件夹下的所有c文件,更改头文件后会重新编译

srcs=$(wildcard *.c)
objs:=$(srcs:.c=.o)
deps:=$(srcs:.c=.d)

CFLAGS=-c -g -Wall

prog:$(objs)
	gcc -o prog $^

-include $(deps)
$(objs):%.o:%.c
	gcc $(CFLAGS) -MMD -MP -MF"$(@:%.o=%.d)" -o $@ $<


.PHONY: clean
clean:
	rm -rf prog *.o *.d
单个文件夹下,编译静态库

srcs:=$(wildcard *.c)
objs:=$(srcs:.c=.o)
deps:=$(srcs:.c=.d)

CFLAGS=-c -g -Wall

prog:libprog.a
	gcc -L. -lprog -o prog 

libprog.a:$(objs)
	ar r libprog.a $(objs)

-include $(deps)
$(objs):%.o:%.c
	gcc $(CFLAGS) -MMD -MP -MF"$(@:%.o=%.d)" -o $@ $<


.PHONY: clean
clean:
	rm -rf prog *.o *.d *.a
单个文件夹下,编译静态库文件,obj文件放入obj文件,d文件放入dep文件夹,静态库文件放入lib文件夹

srcs:=src1.c src2.c src3.c
objs:=$(srcs:.c=.o)
deps:=$(srcs:.c=.d)

vpath %.a ./lib
vpath %.o ./obj

CFLAGS=-c -g -Wall

prog:libprog.a prog.o
	gcc obj/prog.o -L./lib -lprog -o prog 


libprog.a:$(objs)
	ar r lib/libprog.a $(objs:%=obj/%)

-include dep/prog.d
prog.o:prog.c
	gcc $(CFLAGS) -MMD -MP -MF"$(@:%.o=dep/%.d)" -MT"$@" -o obj/$@ $<

-include $(deps:%=dep/%)
$(objs):%.o:%.c
	gcc $(CFLAGS) -MMD -MP -MF"$(@:%.o=dep/%.d)" -MT"$@" -o obj/$@ $<



.PHONY: clean
clean:
	rm -rf prog lib/*.a obj/*.o dep/*.d
单个文件夹下,编译动态库文件
运行程序命令:LD_LIBRARY_PATH=$PWD/lib ./prog

srcs:=$(wildcard *.c)
objs:=$(srcs:.c=.o)
deps:=$(srcs:.c=.d)

CFLAGS=-c -g -Wall -fPIC

prog:libprog.so
	gcc -L. -lprog -o prog 

libprog.so:$(objs)
	gcc -shared -fPIC $(objs) -o libprog.so 

-include $(deps)
$(objs):%.o:%.c
	gcc $(CFLAGS) -MMD -MP -MF"$(@:%.o=%.d)" $< -o $@


.PHONY: clean
clean:
	rm -rf prog *.o *.d *.so

makefile范例