您的位置:首页 > 运维架构 > Linux

Learn to Write Your Makefile

2013-05-28 11:49 369 查看
[实验目的]

1. 掌握基本的Linux下makefile的编写技能

2. 能够阅读常见的makefile

[实验任务]

在linux平台上编译Sonia的一个project:

    [Sonia] Implementation of Huffman Algorithm

将上述工程文件编译成可执行文件huffman 

[基本原理]

1. 依赖关系分析

1) main.cpp   <---  h_tree.h

于是,生成main.o要求: gcc  -c main.cpp  h_tree.h -o main.o

2) h_tree.cpp <--- h_tree.h

于是,生成h_tree.o要求: gcc  -c h_tree.cpp  h_tree.h -o h_tree.o

3) 而生成最终的可执行文件huffman需要将main.o 和 h_tree.o链接起来

于是有: gcc  main.o  h_tree.o -o huffman

由上述分析,可得基本的makefile如下:

huffman: main.o  h_tree.o
g++ main.o h_tree.o -o huffman

main.o: main.cpp  h_tree.h
g++ -c main.cpp -o main.o

h_tree.o: h_tree.cpp h_tree.h
g++ -c h_tree.cpp -o h_tree.o


2. 详细解析

上述makefile中包含了三条如下形式的规则:

**************************************************************************

target: dependenc_file1  dependenc_file2  ... dependenc_filen

<Tab><linux command>

**************************************************************************

main.o: main.cpp  h_tree.h

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

1) main.o 为要生成的目标

2)main.cpp  h_tree.h: 指明为生成main.o的依赖项

3) g++ -c main.cpp -o main.o: 生成main.o需要执行的linux命令

注意:

1)makefile的linux命令(如g++  ,  rm 等均需要以 Tab键(\t)开头 );

2)  makefile的文件应命名为"makefile"或“Makefile” ;

3)  若编写的是c文件,则应调用c语言的编译器gcc。

3. makefile的使用

在含有makefile的目录下,键入命令 “make” 即可

4. 添加make clean

一般地,为了方便地清除编译产生的临时文件,在makefile中会加入一个clean语句。 当欲清理之前编译产生的临时文件时,仅需使用命令“make  clean”即可。

最终的makefile为:

huffman: main.o  h_tree.o
g++ main.o h_tree.o -o huffman

main.o: main.cpp  h_tree.h
g++ -c main.cpp -o main.o

h_tree.o: h_tree.cpp h_tree.h
g++ -c h_tree.cpp -o h_tree.o

clean:
rm -rf *.o huffman


注意:

rm -rf *.o huffman是一条命令,故也应该以Tab键开头

[练习]

1. 为

[Sonia] Implementation of a Binary Tree Sort in C

编写makefile, 要求支持“make” 和 “make  clean” 命令

2. 编写完makefile文件后,输入make命令,观察生成的文件

3. 输入make clean命令,观察消失的文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Makefile Linux