I use three parts(make_test0, make_test1, make_test) to progressive introduction simple makefiles apply for project
1.make_test0(directory)
make_test0 ----Makefile
|----top_main.c
|----hello.c
(1)hello.c -----
#include <stdio.h>
int print_hello(){
printf("hello..........\n");
return 0;
}
(2)top_main.c-----
#include <stdio.h>
extern int print_hello();
int main(){
printf("main............\n");
print_hello();
return 0;
}
(3)Makefile
CC = gcc
CFLAGS = -c
OBJS = $(patsubst %.c, %.o, $(wildcard *.c))
.c.o:
@echo "compile............"
$(CC) $(CFLAGS) -o $@ $<
obj_main:$(OBJS)
@echo "obj_main.........."
$(CC) -o $@ $(OBJS)
.PHONY:clean
clean:
rm -f obj_main $(OBJS)
(4)compile results
xxx@xxx-xx-xxx:~/make_test0$ make
compile............
gcc -c -o hello.o hello.c
compile............
gcc -c -o main.o main.c
obj_main..........
gcc -o obj_main hello.o main.o
2. make_test1
make_test1 ----Makefile
|----top_main.c
|----hello.c
|----include
|----hello.h
|----depend.mk
(1)top_main.c --> it is same as make_test0
(2)hello.c ---> add "hello.h" header file to it.
#include <stdio.h>
#include "hello.h"
int print_hello(void){
printf("hello...%d\n", H_ADD(3,5));
return 0;
}
(3)hello.h ---->it locates at include directory
#define H_ADD(a, b) ((a) + (b))
#define H_DEC(a, b) ((a) - (b))
(4)depend.mk
#第一步执行
include $(patsubst %.c, %.d, $(wildcard *.c))
#第二步执行
%.d: %.c
@set -e; rm -f $@; \
$(CC) -M -Iinclude $< > $@.; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@. > $@;\
rm -f $@.
@echo "hello..............."$@
(5)Makefile
#该变量主要用来指定源文件目录,便于查找源文件
VPATH = print_hello
CC = gcc
#该变量主要用来指定头文件目录
LDFLAGS = -lm -DFORK_CHILDREN=1
INCLUDEFLAGS = -Iinclude
#CFLAGS =
CFLAGS = -c -Wall
SRC = top_main.c \
hello.c
OBJS = $(SRC:.c=.o)
.c.o:
@echo "compile............."$@
$(CC) $(CFLAGS) $(INCLUDEFLAGS) -o $@ $<
#第三步执行
obj_main: $(OBJS)
@echo "obj_main"
$(CC) $(LDFLAGS) -o $@ $(OBJS)
include depend.mk
.PHONY: clean
clean:
rm -f *.d *.o obj_main
(6) compile results
xxx@xxx-xx-xxx:~/make_test1$ make
depend.mk:2: hello.d: No such file or directory
depend.mk:2: top_main.d: No such file or directory
hello...............top_main.d
hello...............hello.d
compile.............top_main.o
gcc -c -Wall -Iinclude -o top_main.o top_main.c
compile.............hello.o
gcc -c -Wall -Iinclude -o hello.o hello.c
obj_main
gcc -lm -DFORK_CHILDREN=1 -o obj_main top_main.o hello.o