<一>编译本地的源文件 + 变量的模式替换 实验代码
root@ubuntu:~/Makefile_Test/5make_test# vim makefile
target := target.out
CC := gcc
src := $(wildcard *.c) #使用maefile的预定义函数来获取本地的后缀为C的源文件
o_files := $(src:%.c=%.o) #这是(变量的高级主题之)变量的模式替换
$(o_files):$(src) #将源代码进行汇编,生成汇编文件
$(CC) -c $^ -o $@
$(target) : $(o_files) #将汇编代码进行链接
@echo $(o_files)
@echo "--------"
$(CC) $^ -o $(target)
测试:
root@ubuntu:~/Makefile_Test/5make_test# ls func1.c makefile root@ubuntu:~/Makefile_Test/5make_test# root@ubuntu:~/Makefile_Test/5make_test# make target.out gcc -c func1.c -o func1.o func1.o -------- gcc func1.o -o target.out
root@ubuntu:~/Makefile_Test/5make_test# make
make: 'func1.o' is up to date. // 这里默认直接make第一个目标,该目标是模式替换内的变量名,应该也存在本文<三>所述问题。详见<三>。
也可以像下面这样写
target := target.out
CC := gcc
src := $(wildcard *.c)
$(target) : $(src)
$(CC) $^ -o $(target)
测试:
root@ubuntu:~/Makefile_Test/5make_test#
root@ubuntu:~/Makefile_Test/5make_test# cat func2.c
#include <stdio.h>
int main(void)
{
printf("hello world \n");
return 0;
}
root@ubuntu:~/Makefile_Test/5make_test# ls
func2.c makefile target.out
root@ubuntu:~/Makefile_Test/5make_test#
root@ubuntu:~/Makefile_Test/5make_test# make
gcc func2.c -o target.out
root@ubuntu:~/Makefile_Test/5make_test# make
make: 'target.out' is up to date.
<二>变量的值的替换 实验
root@ubuntu:~/Makefile_Test/5make_test#
root@ubuntu:~/Makefile_Test/5make_test# cat makefile2
src := a.cc b.cc c.cc
obj := $(src:cc=o) #注意,这里不要有空格
test :
@echo "obj => $(obj)"
root@ubuntu:~/Makefile_Test/5make_test#
root@ubuntu:~/Makefile_Test/5make_test# make -f makefile2 test
obj => a.o b.o c.o
root@ubuntu:~/Makefile_Test/5make_test#
<三>规则中的模式替换 实验
.PHONY : all
cc := gcc
objs := func.o main.o
$(objs) : %.o : %.c #这里的objs是变量名,同时也作为最终make时候的目标名。实测,不可行。
$(cc) -o $@ -c $^#规则替换,等效于下面的几句
#func.o : func.c
# gcc -c $^ -o $@
#main.o : main.c
# gcc -c $^ -o $@
测试
root@ubuntu:~/Makefile_Test/5make_test# make gcc -o func.o -c func.c // 死活,只能打印一句func.c相关的, 但是main.c(每次实验都已保证该文件是最新的) main.o一直不能打印出来 root@ubuntu:~/Makefile_Test/5make_test#
最终的解决方法:
.PHONY : all
cc := gcc
objs := func.o main.o
$(objs) : %.o : %.c
$(cc) -o $@ -c $^
#在原基础上,增加了下述代码
all : $(objs) # 不把objs变量直接作为最终的目标,而是作为依赖来使用
@echo "OK"
#规则替换,等效于下面的几句
#func.o : func.c
# gcc -c $^ -o $@
#main.o : main.c
# gcc -c $^ -o $@
测试
root@ubuntu:~/Makefile_Test/5make_test# ls func.c main.c makefile makefile2 root@ubuntu:~/Makefile_Test/5make_test# root@ubuntu:~/Makefile_Test/5make_test# make all gcc -o func.o -c func.c gcc -o main.o -c main.c OK root@ubuntu:~/Makefile_Test/5make_test# root@ubuntu:~/Makefile_Test/5make_test# ls func.c func.o main.c main.o makefile makefile2
小结:不要将规则中的模式替换代码内的目标,直接作为最终make时候的目标。
来源:https://www.cnblogs.com/happybirthdaytoyou/p/11336743.html