Linux----Makefile

Linux----Makefile

Makefile也是一种脚本(没有后缀就叫Makefile)

Makefile五层
简单的 少的 功能全 看不懂
功能:一次生成编译链接的过程
  make命令:在当前文件夹内找到Makefile的文件,按照其中的内容进行项目编译
  make clean:清楚上一次编译带来的结果

Makefile告诉make有哪些文件,应该怎么处理

目标文件 依赖文件
hello.o hello.c
hello.i hello.o
#Makefile中注释符号
#目标文件:依赖文件
#第二行必须加TAB键,在跟command

#链接
hello:hello.o
  gcc -o hello hello.o
  
#编译
hello.o:hello.S
  gcc -S hello.o -o hello.S

#汇编
hello.S:hello.i
  gcc -S hello.S -o hello.i
#预编译
hello.i:hello.c
  gcc -E hello.c -o hello.i
#倒着写是因为一种索引关系的存在
.PHONY:
clean:
  rm -rf hello.i hello.o hello.S hello
  echo "gcc complete!"

hello:hello.c
gcc -o hello hello.c
这和上边的编译过程实现结果以一样的

显示规则 隐式规则 变量定义 文件指示 注释

#显示规则
hello.i:hello.c
  gcc -E hello.c -o hello.i
  • 伪命令 .PHONY:
  • 通配符 * 所有 % 任意一个
    *.o
#变量
OBJ = target
OBJ += target-1 //追加变量 OBJ = target target-1
OBJ := target  //不能追加
----------------------------------
OBJ = Kindle
target = a.o b.o c.o
target += d.o e.o
$ 引用变量
$(OBJ):$(target)
CC := gcc
CCFLAG = -o

  gcc -o hello hello.o
  $(CC) $(CCFLAG) hello hello.o
#隐含规则
  自动编译的规则
%.o:%.c
  gcc -c %.c -o %.o
#自动变量
$^:代表依赖文件
$@:代表目标文件
$<:第一个依赖文件
$(OBJ):$(target)
  $(CC) $(CCFLAG) $^ $@
%.o:%.c
  $(CC) $(CCFLAG) $^ $@
.PHONY:
clean:
  rm -rf *.o target
  echo "gcc complete!"
gcc选项
-g debug
-Wall 以最高级报警报
-O 0 1 2 3优化等级
---------------------------------
-c -I -D -l 不能连着写
-I 指定头文件的文件夹
-I path
  -I /work/inc
-D 编译时传入宏定义
  gcc -g -DDEBUG main.c -o main
-l 指定动态链接库(.so)
-lpthread
#使用函数
#函数调用方式 $(函数名 参数)
SRC = $(wildcard *.c)
#遍历当前文件夹 获取参数指定文件
OBJ = $(patsubst %.c,%.o,&(SRC))
#把.c替换成.o
#.h会自动匹配
CC := gcc
CCFLAG = -g
all:$(PROG)
$(PROG):$(OBJ)
  $(CC) $(CCFLAG) $^ -o $@
.PHONY:
clean:
  rm -rf *.o target
  @echo "gcc complete!"
#Makefile包含
#主文件夹包含子文件下的
OBJ-y += display/
OBJ-y += debug/
OBJ-y += file/
本文出自T-大帅的博客,转载必须注明出处。 https://www.cnblogs.com/Monarch-T/
原文地址:https://www.cnblogs.com/Monarch-T/p/10335728.html