一.特殊变量的含义
例子:
.PHONY : all out
all out :
@echo "$(MAKE)"
@echo "$(MAKECMDGOALS)"
@echo "$(MAKEFILE_LIST)"
mhr@ubuntu:~/work/makefile1$ make
make // 当前解释器所对应的文件名就是 make
//make 这个应用程序的命令行参数 为空 没有带目标名
makefile //空格 + 当前makefile
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make all //携带了目标名(make这个应用程序的命令行参数)
make // 当前解释器所对应的文件名就是 make
all //make 这个应用程序的命令行参数 目标名 all
makefile //空格 + 当前makefile
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make all out //让 make 执行两个目标
make //先执行 all 目标
all out
makefile
make //再执行 out 目标
all out
makefile
mhr@ubuntu:~/work/makefile1$
二.变量的替换
实验:
src1 := a.cc b.cc c.cc
obj1 := $(src1:cc=o)
test1 :
@echo "obj1 => $(obj1)"
//成功进行了 变量值的替换
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make test1
obj1 => a.o b.o c.o
mhr@ubuntu:~/work/makefile1$
实验:
src2 := a11b.c a22b.c a33b.c
obj2 := $(src2:a%b.c=x%y)
test2 :
@echo "obj2 => $(obj2)"
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make test2
obj2 => x11y x22y x33y
mhr@ubuntu:~/work/makefile1$
实验:
CC := g++
TARGET := hello-makefile.out
OBJS := func.o main.o const.o
$(TARGET) : $(OBJS)
$(CC) -o $@ $^
$(OBJS) : %.o : %.c
$(CC) -o $@ -c $^
.PHONY : rebuild clean all
rebuild : clean all
all : $(TARGET)
clean :
$(RM) *.o $(TARGET)
const.c
const char* g_hello = "hello makefile";
func.c
#include "stdio.h"
extern char* g_hello;
void foo()
{
printf("void foo() : %s\n", g_hello);
}
main.c
extern void foo();
int main()
{
foo();
return 0;
}
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make
g++ -o func.o -c func.c
g++ -o main.o -c main.c
g++ -o const.o -c const.c
g++ -o hello-makefile.out func.o main.o const.o
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ ./hello-makefile.out
void foo() : hello makefile
mhr@ubuntu:~/work/makefile1$
三.变量值的嵌套引用
一个变量名之中可以包含对其他变量的引用
嵌套引用的本质是使用一个变量表示另一个变量
命令行变量:
运行make时,在命令行定义变量
命令行变量默认覆盖makefile中定义的变量
override关键字:
用于指示makefile中定义的变量不能被覆盖
变量的定义和赋值都需要使用override关键字
hm := hello makefile
override var := override-test
test :
@echo "hm => $(hm)"
@echo "var => $(var)"
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make
hm => hello makefile
var => override-test
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make hm:=cmd-hm var:=cmd-var
hm => cmd-hm
var => override-test
mhr@ubuntu:~/work/makefile1$
在命令行中没有被定义的变量在makefile 中是可以直接使用的
test :
@echo "foo => $(foo)"
mhr@ubuntu:~/work/makefile1$ make
foo =>
mhr@ubuntu:~/work/makefile1$
mhr@ubuntu:~/work/makefile1$ make foo:=cmd-foo
foo => cmd-foo
mhr@ubuntu:~/work/makefile1$
define关键字:
用于在makefile中定义多行变量
多行变量的定义从变量名开始到endef结束
define定义的变量等价于使用=定义变量
define foo
I'm fool!
endef
override define cmd
@echo "run cmd ls ..."
@ls
endef
test :
@echo "foo => $(foo)"
${cmd}
mhr@ubuntu:~/work/makefile1$ make
foo => I'm fool!
run cmd ls ...
clean const.c const.o func.c func.o hello-makefile.out main.c main.o makefile
mhr@ubuntu:~/work/makefile1$