学习Makefile的过程中发现了一个讲解很详细的例子,顺便学习一下用remake这个工具来debug Makefile
准备源代码和Makefile
- 就是原文中的第四版Makefile
admin@ubuntu20:~/test_makefile$ cat fun1.c
#include <stdio.h>
void fun1()
{
printf("this is fun1\n");
}
admin@ubuntu20:~/test_makefile$
admin@ubuntu20:~/test_makefile$ cat fun2.c
#include <stdio.h>
void fun2()
{
printf("this is fun2\n");
}
admin@ubuntu20:~/test_makefile$
admin@ubuntu20:~/test_makefile$ cat main.c
#include <stdio.h>
void fun1();
void fun2();
int main()
{
printf("hello world\n");
fun1();
fun2();
}
admin@ubuntu20:~/test_makefile$
admin@ubuntu20:~/test_makefile$ cat Makefile
src = $(wildcard ./*.c)
obj = $(patsubst %.c, %.o, $(src))
#obj = $(src:%.c=%.o)
target = app
CC = gcc
$(target): $(obj)
$(CC) $(obj) -o $(target)
%.o: %.c
$(CC) -c $< -o $@
.PHONY: clean
clean:
rm -rf $(obj) $(target)
admin@ubuntu20:~/test_makefile$
注意Makefile的缩进要用tab而不是空格
安装remake
$ sudo apt install remake -y
debug Makefile
- 启动debug模式
admin@ubuntu20:~/test_makefile$ remake --debugger
Reading makefiles...
Updating makefiles....
Updating goal targets....
-> (/home/admin/test_makefile/Makefile:7)
app: fun1.o fun2.o main.o
remake<0>
- 执行Makefile line 7,发现.o文件不存在
remake<0> n
File 'app' does not exist.
-- (/home/admin/test_makefile/Makefile:7)
app: fun1.o fun2.o main.o
remake<1>
- 先要生成这些.o文件,可以自行查看运行的顺序
remake<1> n
File 'fun1.o' does not exist.
Must remake target 'fun1.o'.
Makefile:11: update target 'fun1.o' due to: fun1.c
##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
gcc -c fun1.c -o fun1.o
##<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Successfully remade target file 'fun1.o'.
File 'fun2.o' does not exist.
Must remake target 'fun2.o'.
Makefile:11: update target 'fun2.o' due to: fun2.c
##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
gcc -c fun2.c -o fun2.o
##<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Successfully remade target file 'fun2.o'.
File 'main.o' does not exist.
Must remake target 'main.o'.
Makefile:11: update target 'main.o' due to: main.c
##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
gcc -c main.c -o main.o
##<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Successfully remade target file 'main.o'.
Must remake target 'app'.
Makefile:8: update target 'app' due to: fun1.o fun2.o main.o
##>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
gcc ./fun1.o ./fun2.o ./main.o -o app
##<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
Successfully remade target file 'app'.
admin@ubuntu20:~/test_makefile$
admin@ubuntu20:~/test_makefile$ ./app
hello world
this is fun1
this is fun2
admin@ubuntu20:~/test_makefile$