学习自狄泰软件学院唐佐临老师Makefile课程,文章中图片取自老师的PPT,仅用于个人笔记。
实验1:变量值的替换
实验2:变量的模式替换
实验3:规则中的模式替换
实验4:命令行变量和override关键字
实验5:在命令行中定义的变量在makefile 中是可以直接使用的
实验6:define 关键字的使用
实验说明
#定义一个变量,变量的值是 a.cc b.cc c.cc
src1 := a.cc b.cc c.cc
#定义变量 obj1,通过变量的值的替换 给obj1初始值
obj1 := $(src1:cc=o)
test1 :
@echo "obj1 => $(obj1)"
#定义一个变量src2 ,变量的值是 a11b.c a22b.c a33b.c
src2 := a11b.c a22b.c a33b.c
#定义变量 obj2 ,初始值由 变量的模式替换得到
obj2 := $(src2:a%b.c=x%y)
test2 :
@echo "obj2 => $(obj2)"
实验1:变量值的替换
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$
实验2:变量的模式替换
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$
注意: 变量的值替换和模式替换中的 % 通配一个字符串
实验3 :规则中的模式替换
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$
好处显而易见,如果还按照 第五课 实验2 的写法,如下。那么添加 const.c的时候需要添加如下代码:
$(TARGET) : func.o main.o const.o
const.o : const.c
$(CC) -o $@ -c $^
而且 也不简洁,但是使用了 规则中的模式替换之后 代码量显而易见,只需要添加一处就可以了
说明:
# 定义变量x 值为y 此处的y 是一个文本类型的字符串
x := y
#定义变量y 值为z 此处的y 和上面的y 不是一回事,这里的y 是一个变量,上一个y 是一个文本值
y := z
a := $($(x))
注意:如果多行命令的值是命令的话,一定要在前面加上 Tab键
实验4 : 命令行变量和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$
实验5: 在命令行中定义的变量在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$
实验6 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$