Makefile例子

开始学习Makefile,看了一天的文档,总要写点什么东西,不然看完又该忘记了。于是,有了下面的小例子。

例子包含了三个子文件夹sayhello , dowork , saybye。

文件learn_makefile/sayhello/hello.c的内容如下

#include <stdio.h>
#include "hello.h"

int sayHello(char* name){
  printf("Hello %s!\n",name);
  return 1;
}

文件learn_makefile/sayhello/hello.h的内容如下

#include <stdio.h>
int hello(char*);

文件learn_makefile/dowork/work.c的内容如下

#include <stdio.h>
#include "work.h"

int doWork(){
  printf("I am working... ...\n");
  return 1;
}

文件learn_makefile/dowork/work.h的内容如下

#include <stdio.h>

int work();

文件learn_makefile/saybye/bye.c的内容如下

#include <stdio.h>
#include "bye.h"

int sayBye(char* name){
  printf("Bye %s!\n",name);
  return 1;
}
文件learn_makefile/saybye/bye.h的内容如下

#include <stdio.h>

int bye(char*);

文件learn_makefile/example.c的内容如下

#include <stdio.h>
#include "sayhello/hello.h"
#include "dowork/work.h"
#include "saybye/bye.h"

int main(){

  char *name = "Steven";
  sayHello(name);
  doWork();
  sayBye(name);
  return 1;

}

程序运行后的输出是:
[stevenqin@rat081 learn_makefile]$ ./example
Hello Steven!
I am working... ...
Bye Steven!

很显然,最简单的Makefile可以写作如下,这个没有什么难度

CC=gcc
object = example.o hello.o bye.o work.o

example:$(object)
	$(CC) -o example $(object)

hello.o : ./sayhello/hello.c
	$(CC) -c ./sayhello/hello.c
work.o : ./dowork/work.c
	$(CC) -c ./dowork/work.c
bye.o : ./saybye/bye.c
	$(CC) -c ./saybye/bye.c
example.o : example.c ./sayhello/hello.h ./dowork/work.h ./saybye/bye.h
	$(CC) -c example.c

clean:
	rm example $(object)


然后解决的是路径的问题。

首先要了解VPATH的意义:

全局访问路径::即在执行make命令时可以从该路径中查询目标和依赖make可识别一个特殊变量“VPATH”。通过变量“VPATH”可以指定依赖文件的搜索路径,
在规则的依赖文件在当前目录不存在时,make会在此变量所指定的目录下去寻找这些依赖文件。一般我们都是用此变量来说明规则中的依赖文件的搜索路径。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值