3.make_test
make_test-|----Makefile
|----top_main.c
|----print_hello
|----hello.c
|----Makefile
|----print_world
|----world.c
|----Makefile
|----include
|----hello.h
|----world.h
|----depend.mk
(1)top_main.c
#include <stdio.h>
extern int print_world();
extern int print_hello();
int main(){
printf("print top_main.......\n");
print_hello();
print_world();
return 0;
}
(2)hello.c world.c
//hello.c
#include <stdio.h>
#include "hello.h"
int print_hello(void){
printf("hello...%d\n", H_ADD(3,5));
return 0;
}
//world.c
#include <stdio.h>
#include "world.h"
int print_world(){
printf("world...%d\n", W_DEC(9,1));
return 0;
}
(3)hello.h world.h
//hello.h
#define H_ADD(a, b) ((a) + (b))
#define H_DEC(a, b) ((a) - (b))
//world.h
#define W_DEC(a, b) ((a)-(b))
#define W_ADD(a, b) ((a)+(b))
(4)depend.mk
%.d: %.c
@set -e; rm -f $@; \
$(CC) -M $(INCLUDEFLAGS) $< > $@.; \
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@. > $@;\
rm -f $@.
@echo $@"..........d"
(5)Makefile
#1.---------顶层Makefile-------------------------------
#该变量主要用来指定源文件目录,便于查找源文件
VPATH = print_hello print_world
CC = gcc
CFLAGS = -c
#该变量主要用来指定头文件目录
INCLUDEFLAGS = -Iinclude
LDFLAGS = -lm -DFORK_CHILDREN=1
SRC = top_main.c \
hello.c \
world.c
OBJS = $(SRC:.c=.o)
.c.o :
$(CC) $(CFLAGS) $(INCLUDEFLAGS) -o $@ $<
#第三步执行
obj_main: $(OBJS)
@echo "obj_main-----------"$@
$(CC) $(LDFLAGS) -o $@ $(OBJS)
#第一步执行
include $(patsubst %.c, %.d, $(wildcard *.c))
include $(patsubst %.c, %.d, $(wildcard print_hello/*.c))
include $(patsubst %.c, %.d, $(wildcard print_world/*.c))
#第二步执行
include depend.mk
.PHONY: clean
clean:
$(MAKE) -C print_hello
$(MAKE) -C print_world
rm -f *.d *.o obj_main
#2.-----print_hello目录下Makefile
.PHONY: clean
clean:
rm -f *.d
#3.-----print_world目录下Makefile
.PHONY: clean
clean:
rm -f *.d
(6) compile and clean results
#compile results--------------------------------------------------
xxxx@xxx-xx-xxxx:~/make_test$ make
Makefile:27: top_main.d: No such file or directory
Makefile:28: print_hello/hello.d: No such file or directory
Makefile:29: print_world/world.d: No such file or directory
print_world/world.d..........d
print_hello/hello.d..........d
top_main.d..........d
gcc -c -Iinclude -o top_main.o top_main.c
gcc -c -Iinclude -o hello.o print_hello/hello.c
gcc -c -Iinclude -o world.o print_world/world.c
obj_main-----------obj_main
gcc -lm -DFORK_CHILDREN=1 -o obj_main top_main.o hello.o world.o
#clean results-----------------------------------------------------
xxxx@xxx-xx-xxxx:~/make_test$ make clean
make -C print_hello
make[1]: Entering directory '/home/cdlab/make_test/print_hello'
rm -f *.d
make[1]: Leaving directory '/home/cdlab/make_test/print_hello'
make -C print_world
make[1]: Entering directory '/home/cdlab/make_test/print_world'
rm -f *.d
make[1]: Leaving directory '/home/cdlab/make_test/print_world'
rm -f *.d *.o obj_main
Conclusion: depend.mk is very convenient for us to find the relationship between .o file and .c and .h file
such as -> hello.o : hello.c hello.h....