makefile 实例

最近玩了下linux下c编程,觉得makefile对于项目管理有很大的优越性,在此跟大家分享,如有不足之处敬请指正。

 

系统:Red Hat Enterprise Linux 5

编辑工具 vi,vim(更好用,带有关键字高亮功能)

我自己写了个hello world的小例子,一个头文件:sayhello.h,两个源文件:sayhello.c hello.c

 

/*sayhello.h*/

#ifndef SAY_HELLO          //这块的宏只是为了条件编译,防止重复声明
#define SAY_HELLO  

void sayhello ();               //声明sayhello()函数
#endif

 

/*sayhello.c*/        

#include<stdio.h>
#include"sayhello.h"       //包含头文件

void sayhello()                 //sayhello()函数的真正实现
{
printf("Hello World!\n我会时常想洋洋\n");   //向控制台打印 Hello World!
}

 

 

/*hello.c*/

#include"sayhello.h"       //包含头文件
int main ()
{
sayhello();                      //sayhello()函数调用
return 0;

}

 

以上三个文件放于一个目录下,一般情况下,我们是这样做的:

 

切换到文件目录下

。。。。。。

[root@wuzhq hellotest]# ls
hello.c  sayhello.c  sayhello.h 
[root@wuzhq hellotest]# gcc -c sayhello.c    //将sayHello.c编译为目标文件sayhello.o
[root@wuzhq hellotest]# gcc -c hello.c           //将hello.c编译为目标文件hello.o
[root@wuzhq hellotest]# gcc -o hello hello.o sayhello.o     //将sayhello.o hello.o统一连接为可执行文件hello
[root@wuzhq hellotest]# ./hello

Hello World!

我会时常想洋洋

 

当然我们也可以这样来做:

[root@wuzhq hellotest]# ls
hello.c  sayhello.c  sayhello.h 
[root@wuzhq hellotest]# gcc -o hello hello.c sayhello.c       //一步到位,gcc将多个源文件编译为一个可执行文件有它自己内置的规则

 

 

大家试想,如果对于一个较大型的项目,跟多文件,如改动一处,我们是不是还是要一步步的重复敲命令,重复编译,重复连接?有没有跟好的解决办法呢?答案是肯定的,这时就体现出了makefile的优势

 

在源文件所在目录新建makefile,我自己命名为test,文件内容:

hello:hello.o sayhello.o
        gcc -o hello hello.o sayhello.o
hello.o:hello.c sayhello.h
        gcc -c hello.c
sayhello.o:sayhello.c sayhello.h
        gcc -c sayhello.c
[root@wuzhq hellotest]# ls 

hello.c  sayhello.c  sayhello.h  test

[root@wuzhq hellotest]# make -f test
gcc -c hello.c
gcc -c sayhello.c
gcc -o hello hello.o sayhello.o
[root@wuzhq hellotest]# ls
hello  hello.c  hello.o  sayhello.c  sayhello.h  sayhello.o  test

[root@wuzhq hellotest]# ./hello

Hello World!

我会时常想洋洋

 

看出它的优势了吧,每次对已有文件作改动时,改动之后只需执行make -f test就可以得到新的可执行文件hello

在Makefile中也#开始的行都是注释行.Makefile中最重要的是描述文件的依赖关系的说明。一般的格式是: 
target:components 
TAB rule 
第一行表示的是依赖关系。第二行是规则。特别注意规则行一定要以tab键开头,我上次就犯过这样的错误。

关于makefile编写详细的说明可参考http://www.360doc.com/content/10/0904/22/507289_51249378.shtml,我觉得是个不错的材料。

希望对大家有帮助。

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值