开始学习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会在此变量所指定的目录下去寻找这些依赖文件。一般我们都是用此变量来说明规则中的依赖文件的搜索路径。