Makefile学习记录

1 创建文件

test1.c/h test2.c/h

  • test1.c
#include <stdio.h>
#include "test1.h"

void test_fun1(void){
    printf("Hello Makefile-----1\n");
}
  • test.h
#ifndef __TEST1_H__
#define __TEST1_H__

void test_fun1(void);

#endif
  • test2.c
#include <stdio.h>
#include "test2.h"

void test_fun2(void){
    printf("Hello Makefile ---->2\n");
}
  • test2.h
#ifndef __TEST2_H__
#define __TEST2_H__

void test_fun2(void);

#endif

2 gcc编译看看测试代码是否正确

gcc *.c -o test
ls
Makefile  main.c  test  test1.c  test1.h  test2.c  test2.h
./test
Hello Makefile-----1
Hello Makefile ---->2

编写简单的makefile

2.1 makefile格式

target: prerequisites
	commands

#  即:
#  目标文件: 依赖项
#  		命令

2.2 分析

可执行文件由编译+链接生成
假设可执行文件为test:

  • test是main.o test1.o test2.o链接而成的
  • main.o 是main.c编译生成的
  • test1.o 是test1.c编译生成的
  • test2.o 是test2.c编译生成的

2.3 初试

根据上面的分析以及makefile的格式,可以简单这样写

tests:main.o test1.o test2.o 
	gcc main.o test1.o test2.o -o test_makefile

main.o:main.c
	gcc main.c -c -Wall -g -o main.o

test1.o:test1.c
	gcc test1.c -c -Wall -g -o test1.o

test2.o:test2.c
	gcc test2.c -c -Wall -g -o test2.o

.PHONY:clean
clean: 
	rm -rf *.o test_makefile

在命令行make进行编译:

> make
gcc main.c -c -Wall -g -o main.o
gcc test1.c -c -Wall -g -o test1.o
gcc test2.c -c -Wall -g -o test2.o
gcc main.o test1.o test2.o -o test_makefile

> ls
Makefile  main.c  main.o  test1.c  test1.h  test1.o  test2.c  test2.h  test2.o  test_makefile
> ./test_makefile
Hello Makefile-----1
Hello Makefile ---->2

2.4 加入静态模式的语法进行优化

CC = gcc
CFLAGS = -c -Wall -g
OBJS = main.o test1.o test2.o

test_makefile:$(OBJS)
	$(CC) $^ -o test_makefile

$(OBJS): %.o:%.c
	$(CC) $^ $(CFLAGS) -o $@

.PHONY:clean
clean: 
	rm -rf *.o test_makefile

运行结果:

> make
gcc main.c -c -Wall -g -o main.o
gcc test1.c -c -Wall -g -o test1.o
gcc test2.c -c -Wall -g -o test2.o
gcc main.o test1.o test2.o -o test_makefile
> ls
Makefile  main.c  main.o  test1.c  test1.h  test1.o  test2.c  test2.h  test2.o  test_makefile
> ./test_makefile
Hello Makefile-----1
Hello Makefile ---->2

2.5 说明

  • 变量:
    CC、CFLAGS均为定义的变量,用于能够简单的对参数进行重复使用

  • $系列

$@: 表示目标文件
$^: 表示所有的依赖文件
$<: 表示第一个依赖文件
%?: 表示比目标还要新的依赖文件列表
  • .PHONY:
    .PHONY后面的target表示的是一个伪造的target,指定一个假的target,表示target并不是一个实际的文件。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值