一.makefile 基础认识

来源:互联网 发布:ewb仿真软件下载 编辑:程序博客网 时间:2024/06/05 21:10

makefile 本质上是定义可一套规则,对工程源进行编译 程序链接,先举一个小例子以展开makefile的讲解,其他makefile 具体含义和好处 不详谈;

首先建立一个test文件,然后建立三个文件百度分享 (http://pan.baidu.com/s/1miRnbtu)
mkdir test
cd test
touch hello.cpp
vi hello.cpp然后输入代码
touch test.h
vi test.h 然后输入代码
touch makefile
vi makefile 然后输入规则

#include<iostream>using namespace std;void print(){cout<<"i am a student"<<endl;}

test.h源文件

#include"test.h"#include<iostream>using namespace std;int main(int argc,char* argv[]){cout<<"hello world"<<endl;print();return 0;}

hello.cpp源文件

object=hello.o hello:$(object)    g++  -o hello -g $(object)$(object):hello.cpp test.h    g++ -o $(object) -c hello.cpp clean:    rm hello $(object)

makefile 文件

简要说一下源文件 只是一个普通的”hello world” 程序,在ubuntu 环境下 只输入 g++ hello.cpp -o hello之后执行 ./hello 即输出结果,工程文件很少的时候,这样直接键入命令操作是很简单的,但是当工程量很大的时候,文件很多的时候,makefile的优势就会显现出来,先简单详细的分析一下makefile的语法规则。

makefile 最基本的语法规则是

target:prerequisites

[tab]command

clean:

[tab]rm prerequisites

以此为基准展开makefile的讲解,makefile实际就是符合它的基本语法的前提下,ubuntu编译命令的有顺序执行;

首先源代码执行需要经历三个阶段 源文件– 链接文件 —二进制执行文件,make在执行解析makefile过程中也为这一目标解析;

makefile 执行也遵循这一过程,(以上述makefile执行过程为例进行分析)

首先当在ubuntu命令行中执行make 的时候,make 会在所在的test文件夹下搜索makefile (当然也可以是Makefile )执行,当文件夹下存在多个makefile 的时候(比如存在makefile Makefile 两个文件) 我们可以执行make -f 名字 执行指定的makefile (Makefile)

  • 执行make makefile 进行解析,首先遇到一行变量语句object=hello.o,object 为makefile的变量名字,类似c语言变量名字语法一样,这个变量名字可以随便起,方便识别期间,最好见文生意,
    hello.o代表生成的链接文件,这里是将下面语句生成过程中链接文件用object变量的名字替代,因此在下面的语法规则里面,我们可以使用$(object)
    表示变量object
    就代表hello.o文件,当然也可以不使用这句,一律还是用hello.o;但是当链接文件很多的时候,这样做还是很好的;
object=hello.o
  • 然后遇到最终要生成的可执行二进制文件hello
    ,它依赖于链接文件hello.o,,然后下一行需要书写二进制文件hello生成过程的命令,要以【tab】起始,g++ -o hello
    -g hello.o 这里使用了-g 是表示生成的目标的文件是是可以debug进行调试运行的,当然也可以执行写成g++ hello.o; 但是当make执行这两行语句的时候发现,当前文件下没有链接文件,然后只能往下寻找下一行语句,以期望获得链接文件;
hello:$(object)    g++  -o hello -g $(object)
  • 源文件生成链接文件,make解析这两行语句 ,hello.o为生成的目标文件,hello.cpp test.h
    为依赖的文件,这两行语句和上面解释雷同,通过源文件生成链接文件。make
    执行完这两行语句,生成链接文件hello.o然后返回执行上两行语句生成可执行文件hello。然后make
    退出执行,完成整个makefile 的解析过程
$(object):hello.cpp test.h    g++ -o $(object) -c hello.cpp 
  • clean 为makefile 清除目标命令 clean 后面可以不加参数,[tab] 之后为clean的具体操作,rm 删除目标文件
clean:    rm hello $(object)
0 0
原创粉丝点击