Makifile 的用法

来源:互联网 发布:新概念英语软件 编辑:程序博客网 时间:2024/06/03 17:14

Linux下对程序的自动编译文件:Makefile

一:认识Makefile

Makefile 是一个描述“如何生成整个项目”的脚本文件

方法:

1)创建一个文件Makefile :torch Makefile

2)输入命令,根据Makefile里面的指示,自动执行所有的步骤:make -f Makefile 或者直接make 不带参数

Makefile的写法:

规则:target:dependencies

<TAB>system command1

<TAB>system command2

<TAB>system command...

target:目标,dependencies,依赖

<TAB>:每行命令前必须插一个TAB

system command:系统命令

也就是说;要完成目标target,必须执行命令commands...

比如:

helloworld:

g++ main.o -o helloworld

一个规则里面可以加多个命令:

        

helloworld:

g++ -c main.cpp -o main.o

g++ -c other.cpp -o other.o

g++ main.o other.o -o helloworld

一个Makefile里面可以有多条规则,比如加个规则clean

clean:

rm -f *.o helloworld

输入make命令时,可以显式指定要执行哪一条规则,比如make clean/make -f Makefile clean



二:增量编译

当某个cpp更新之后,只编译这个cpp文件,其他没有更新的文件不重复编译

Makefile里使用“dependencies”来实现增量编译

依赖:是一个文件列表,当有文件更新时,就执行这条规则

helloworld: main.o other.o//只有当着两个文件其中有一个更新了就执行下面这条规则

g++  main.o other.o -o helloworld

main.o:main.cpp other.h//同理

g++ -c main.cpp -o main.o

如果想要某个规则始终执行的话,就让依赖文件不存在,即依赖为空

时间比较:target(T1),dependency(T2)

1)若target文件不存在,则T1=0;

2)若dependency为空,则T2=0

比较T2与T1:

if(T1==0)执行;else if(T2>T1)执行;else "已是最新,不执行规则"

查看时间 ls -l --full-time


三:注释、变量与函数

以#开头为注释

例如定义变量;SUBDIE = src xml SUBDIR += osapi

定义了一个变量;SUBDIR

test:

echo $(SUUBDIR)

1)用=赋值(等号两侧可以加空格)

2)用+=追加字符串

3)用$(SUUBDIR)取得变量的值

特殊的变量:

$@ 指代target

$^指代dependencies依赖项列表

$<指代依赖项的第一项

Makefile中有一些预定义的函数

$(函数名 参数列表)

函数名: Makefile内部自带的函数

参数列表:以逗号分开

另:函数名和参数列表可以以空格分开

例如: PWD=$(shell pwd)

SOURCES=$(wildcard ./*.cpp)


四:优化Makefile

当文件较多时,如何简化如下的写法

helloworld: main.o other.o

g++  main.o other.o -o helloworld

main.o:main.cpp other.h

g++ -c main.cpp -o main.o

other.o:other.cpp

g++ -c other.cpp -o other.o

1)使用通配符

%.o:%.cpp

g++ -c $< -o $@

使用这一条规则就可以替换

main.o:main.cpp 

g++ -c main.cpp -o main.o

other.o:other.cpp

g++ -c other.cpp -o other.o

2)自动罗列.o文件


SOURCES=$(wildcard ./*.cpp)//罗列函数

OBjects = $(patsubst %.cpp, %.o,$(SOURCES))//替换函数

patsubst:三个部分,原格式,目标格式,文件列表

那么

helloworld: main.o other.o

g++  main.o other.o -o helloworld

可以改为:

helloworld:$(OBjects)

g++ $(OBjects) -o helloworld

3)设置EXE变量,设置输出程序的名字

如果.还有别的依赖项也要加上:

main.o:other.h

other.o:other.h


五:头文件依赖的处理

如上提出的头文件依赖如何自动生成呢?

使用编译项-MMD

然后生成了.d文件

g++ -c MMD main.cpp -o main.o

将所有的.d文件都包含进来

FILES = $(patsubst %.o, %.d, $(SOURCES))

改%.o:%.cpp

g++ -c -MMD $< -o $@

-include $(FILES)


六:支持多个子目录

将统治整个项目的文件Makefile放在根目录

bin文件夹放输出文件,即最终的文件

其他模块文件放在相应的模块目录下


在Makefile中,要自动罗列子目录里面的cpp
用函数foreach

比如cxx_SOURCES = $(foreach dir, $(SUDDIR), $(wildcard $(dir)/*.cpp)

dir:迭代器,遍历$(SUDDIR)下面的子目录





0 0
原创粉丝点击