目录
1、通用主Makefile代码3、Makefile.build2、子Makefile
1、通用主Makefile代码
CROSS_COMPILE
=aarch64
-linux
- #这里可以添加编译工具
AS
= $
(CROSS_COMPILE
)as
LD
= $
(CROSS_COMPILE
)ld
CC
= $
(CROSS_COMPILE
)gcc
CPP
= $
(CC
) -E
AR
= $
(CROSS_COMPILE
)ar
NM
= $
(CROSS_COMPILE
)nm
STRIP
= $
(CROSS_COMPILE
)strip
OBJCOPY
= $
(CROSS_COMPILE
)objcopy
OBJDUMP
= $
(CROSS_COMPILE
)objdump
export AS LD CC CPP AR NM #导出给所以目录
export STRIP OBJCOPY OBJDUMP
CFLAGS
:= -Wall
-O2
-g #添加编译选项
CFLAGS
+= -I $
(shell pwd
)/include #指定头文件
LDFLAGS
:= -L $
(shell pwd
)/lib
-labc #指定库的地址
export CFLAGS LDFLAGS
TOPDIR
:= $
(shell pwd
) #顶目录
export TOPDIR
TARGET
:= test #执行文件
obj
-y
+= main
.o #需要编译的文件
obj
-y
+= sub
.o #如果 D 在前面是延时变量,那么现在它还是延时变量;
#如果 D 在前面是立即变量,那么现在它还是立即变量
obj
-y
+= a
/
all
: start_recursive_build $
(TARGET
)
@echo $
(TARGET
) has been built
!
start_recursive_build
:
make -C
./ -f $
(TOPDIR
)/Makefile
.build #我们可以使用“
-f”选项指定文件
#我们可以使用“
-C”选项指定目录,切换到其他目录里去
$
(TARGET
) : built
-in
.o
$
(CC
) -o $
(TARGET
) built
-in
.o $
(LDFLAGS
)
clean
:
rm
-f $
(shell find
-name
"*.o")
rm
-f $
(TARGET
)
distclean
:
rm
-f $
(shell find
-name
"*.o")
rm
-f $
(shell find
-name
"*.d")
rm
-f $
(TARGET
)
3、Makefile.build
这个文件不会给变,只放在主Makefil目录里面,它的作用是去子Makefile里面去编译
PHONY
:= __build
__build
:
obj
-y
:=
subdir
-y
:=
EXTRA_CFLAGS
:=
include Makefile
# obj
-y
:= a
.o b
.o c
/ d
/
# $
(filter
%/, $
(obj
-y
)) : c
/ d
/
# __subdir
-y
: c d
# subdir
-y
: c d
__subdir
-y
:= $
(patsubst
%/,%,$
(filter
%/, $
(obj
-y
)))
subdir
-y
+= $
(__subdir
-y
)
# c
/built
-in
.o d
/built
-in
.o
subdir_objs
:= $
(foreach f
,$
(subdir
-y
),$
(f
)/built
-in
.o
)
# a
.o b
.o
cur_objs
:= $
(filter
-out
%/, $
(obj
-y
))
dep_files
:= $
(foreach f
,$
(cur_objs
),.$
(f
).d
)
dep_files
:= $
(wildcard $
(dep_files
))
ifneq
($
(dep_files
),)
include $
(dep_files
)
endif
PHONY
+= $
(subdir
-y
)
__build
: $
(subdir
-y
) built
-in
.o
$
(subdir
-y
):
make -C $@
-f $
(TOPDIR
)/Makefile
.build
built
-in
.o
: $
(cur_objs
) $
(subdir_objs
)
$
(LD
) -r
-o $@ $
^
dep_file
= .$@
.d
%.o
: %.c
$
(CC
) $
(CFLAGS
) $
(EXTRA_CFLAGS
) $
(CFLAGS_$@
) -Wp
,-MD
,$
(dep_file
) -c
-o $@ $
<
.PHONY
: $
(PHONY
)
2、子Makefile
EXTRA_CFLAGS := -D DEBUG //给整个目录的的.c文件定义这个宏 CFLAGS_sub3.o := -D DEBUG_SUB3 //只给指定的.c文件指定这个宏
obj-y += sub2.o obj-y += sub3.o